I have few questions about string literals in C++.
char *strPtr = "Hello" ;
char strArray[] = "Hello";
Now strPtr
and strArray
are considered to be string literals.
As per my understanding, string literals are stored in read-only memory so we cannot modify their values. We cannot do:
strPtr[2] = 'a';
// or
strArray[2] = 'a';
Both the above statements should be illegal. The compiler should raise errors in both cases, because it keeps string literals in read-only memory, so if we try to modify them, the compiler throws errors.
Also, const
objects are considered read-only.
Is it that both string literals and const
objects are treated same way?
Can I remove const
ness using const_cast
from string literals to change their value?
Where exactly are string literals stored? (In the .data
section of program, I assume.)