I know for a fact that string contents of a pointer is not modifiable.
That's only partially true...
A pointer is in the end just the address of some memory. A pointer of type char
can point to some single character, to the beginning or even into the middle of some array or one past the end of such an array (well, but you need to assign a valid address to a pointer before using it – which is not the case in your main
function: "doesn't work"). You can modify any such array via a pointer, provided the array itself is not const
.
Exactly the same for C strings; actually, these are nothing more than an array stored somewhere in memory. Requirement to be able to interpret the data in this array as 'string' is that the last character part of the actual string data is a null-character (which doesn't necessarily have to be the last character in the entire array), and you can have a pointer to that array (char*
or char const*
).
Now there's the special case of string literals, i. e. any string you define with double quotes: "hello world"
. In reality, these are arrays, too, containing the the contents defined plus the terminating null character. These arrays are immutable albeit not being const.
Normally, they should be const
(just as they are in C++), but string literals existed before const
did – and for compatibility reasons, their type was retained as char*
instead of char const*
when the new keyword finally was introduced.
Still I recommend consistently assigning string literals only to const pointers to avoid undefined behaviour due to modified string literals.