Type str1 - const char* . This is char , not const , not a pointer. That is, it is a pointer to const char . This means that you cannot do this:
str1[0] = 't';
This will change the value of one of const char s.
Now what do you do when you do str2 = "tna"; , the value of the pointer changes. It's great. You just change str2 to point to another string literal. Now str1 and str2 point to different lines.
Using the const const pointer, you can do str2[0] = 't'; - however, you will have undefined behavior. You cannot change something that was originally declared const . In particular, string literals are stored in read-only memory, and trying to change them will lead to a terrible misfortune.
If you want to take a string literal and change it safely, initialize the array with it:
char str1[] = "david";
This will copy the characters from the string literal to the char array. Then you can change them to your liking.
Joseph mansfield
source share