I wrote this short program
int main(){
char * c = "abcd";
c[1] = '\0';
cout << c << endl;
}
and it doesn’t work… actually it compiles the program but in the runtime an error occures…
Why? I thought it will print an “a” as the “string” now looks like this: “a0cd” so after a zero it is supposed to detect an end of the string, right? So where is the problem?
Thank you!
You can’t modify string literals like that.
Try this instead:
The reason behind this is that string literals are stored in global memory (often in a read-only segment). Modifying them is undefined behavior. However, if you initialize it as an array
char c[] = "abcd"it will be on the stack (as opposed to global memory), so you can freely modify it.