This is a question based on answers from question:
const char myVar* vs. const char myVar[]
const char* x = "Hello World!";
const char x[] = "Hello World!";
I understand the difference now, but my new questions are:
(1) What happens to the “Hello World” string in the first line if I reassign x? Nothing will be pointing to it by that point – would it be destroyed when the scope ended?
(2) Aside from the const-ness, how are the values in the two examples differently stored in memory by the compiler?
Placing
"Hello World!"in your code causes the compiler to include that string in the compiled executable. When the program is executed that string is created in memory before the call tomainand, I believe, even before the assembly call to__start(which is when static initializers begin running). The contents ofchar * xare not allocated usingnewormalloc, or in the stack frame ofmain, and therefore cannot be unallocated.However, a
char x[20] = "Hello World"declared within a function or method is allocated on the stack, and while in scope, there will actually be two copies of that"Hello World"in memory – one pre-loaded with the executable, one in the stack-allocated buffer.