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?
The main difference between them is that the first is an array and the other one is a pointer. The array owns its contents, which happen to be a copy of "Test" , while the pointer simply refers to the contents of the string (which in this case is immutable). Why is char* str commonly used when str denotes a string.
For the array, the total string is stored in the stack section, but for the pointer, the pointer variable is stored into stack section, and content is stored at code section. And the most important difference is that, we cannot edit the pointer type string. So this is read-only.
In C, an array of type char is used to represent a character string, the end of which is marked by a byte set to 0 (also known as a NUL character)
char a[]="string"; // a is an array of characters. char *p="string"; // p is a string literal having static allocation. Any attempt to modify contents of p leads to Undefined Behavior since string literals are stored in read-only section of memory.
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 to main
and, I believe, even before the assembly call to __start
(which is when static initializers begin running). The contents of char * x
are not allocated using new
or malloc
, or in the stack frame of main
, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With