C Language Learning 005: strings that cannot be modified, C Language Learning 005 string
Can you see a piece of problematic code?
1 int main () {2 char * msg = "ABC"; 3 msg [0] = msg [1]; 4 puts (msg); 5 return 0; 6}
Compiling this Code does not have any problem. A running program crashes because it modifies the value of the constant area in the memory.
When a computer loads a program into the memory, all constants are placed in the constant storage zone, which is read-only.
To change the content of a string, you need to perform operations on its copy, that is, copy the content of the string to a non-read-only region.
So what is the difference between this and the previous Code area? The pointer pointing to the read-only area is used in the original code. We use the pointer to modify the value of the string, and the string corresponding to the pointer is in the read-only area, we Initialize an array using a string literal, that is, copying the read-only string to a non-read-only region, so that we can modify the copy at will.
To avoid further modification of the read-only region, we can add the const keyword when declaring the pointer so that the program can avoid such errors during compilation.
There is no error in assigning a pointer to the literal of a string. The error is that the value of the string is modified.