+ 2

Pointers Confusion

Key confusions What i understood from chatbot(requires a bit hardware knowledge which i don't have) 1.char* ptr = "String" means ptr points to a read-only string. often in the .rodata section of the program. 2.Reassigning ptr just changes the pointer, not the original string. ptr now points to a new string .The old string still exists in memory, but ptr no longer points to it. 3.String literals are statically allocated by the compiler. They exist before your program runs (loaded into memory when the executable starts). But 1 question remains : Isn't character array, an array therefore a pointer itself?How could there be 2 variants in declaration then? https://sololearn.com/compiler-playground/cz70783YtI4t/?ref=app

25th Jul 2025, 5:18 PM
Nahid Alom Neshad (Nahid)
Nahid Alom Neshad (Nahid) - avatar
3 odpowiedzi
0
All you said is correct. Literals are meant to be read only and put in read only static memory. So... char * mystring = "hello world"; "hello world" is in read only static memory. there are hacky ways to modify it though, but technically it is meant to be read only or if you try modify it it is undefined behavior. the char * mystring is a pointer and its value is on the stack if it is declared inside a function. char arr[] = {'a', 'b', 'c', '\0'}; // this whole thing is also on the stack, if arr is inside a function same with char arr[] = "abc"; otherwise global vars are in data segment, not read only
25th Jul 2025, 7:39 PM
The Witcher
The Witcher - avatar
0
oh and then... if you do new char[69]; or if you use malloc, then that memory is in heap memory
25th Jul 2025, 7:45 PM
The Witcher
The Witcher - avatar
0
oh and then alsoooooo the main command line arguments and environment variables.... they are further down where the stack is. not sure what it is called but they have a special place just for them too. int main(int argc, char ** argv, char ** env) <- these three parameters
25th Jul 2025, 7:54 PM
The Witcher
The Witcher - avatar