You have to understand that there is a difference between the following two lines:
char myArray[] = "Hello Mars!";
char* myPointer = "Hello World!";
The first one creates an array of chars, which can be manipulated. The whole array will be allocated on the stack.
The second one initializes a pointer to char with a string literal (a special construct from the C language allows this). This is to be considered a constant. You will get the address of it, but it is an array of const chars really. The implementation is as follows:
The string will be stored literally in your executable image in memory (as an identical copy of the file on hdd), and you will get the pointer to that string. Space will be made on the stack for the pointer myPointer
. Consider the string literal like a literal number in your code (yes, the magic numbers I'm talking about). The compiler needs to store those characters somewhere, but it is not the kind of memory you will normally work with in your program. It is not on the heap, nor on the stack. See the answer to the following question for more info:
http://stackoverflow.com/questions/1169858/global-memory-management-in-c-in-stack-or-heap
edit: about pointers and arrays
It is not the char*
that makes it immutable, but the string literal. Pointers and arrays are very much related. An array will very often behave like a pointer. Considering the code above this is completely legal:
myPointer = myArray;
myPointer
was not const and you can change it to point to the address of myArray
instead of the string literal. The address it pointed to was read-only. Now myPointer
points to the adress on the stack where "Hello Mars!"
is stored. You could now write:
myPointer[3] = 'Z';
If you want to get a torough understanding of this, read some tutorial like this one.
on constness
Const can be confusing especially with pointers.
const char* const myPointer2 = myPointer;
The first const makes the characters const, so you cannot use myPointer2
to change them, and the second const makes the pointer itself const, so you cannot let it point to something else like myPointer2 = myArray;
See this explanation for more info.