char arr[] = "Hello"
stores a modifiable copy of the string literal "Hello"
in the char array arr
, the p_str1
variable is a pointer to that array, since the data is modifiable the pointer does not need to be const
.
char *p_str3 = "Hello"
is a pointer directly to a string literal that is read-only. The pointer does not own the string literal, more often than not these are stored in some read-only section of memory, either way you can access the data, but you can't modify it. Making the const
pointer obligatory avoids undesired problems at runtime.
The C++ standard does not allow for non-const pointers to unmodifiable data. And that is fortunate because it avoids undefined behavior by way of attempting to modify it, as often happens in C where this rule doesn't exist.
It was still legal to use non-const char
pointer in C++03 (perhaps for legacy reasons), when it was deprecated, after C++11 it was disallowed. As far as I can tell attempting to modify these string literals was always undefined behavior.