the following code can be compiled correctly on both VC or gcc:
char *str = "I am a const!";
str[2] = 'n';
however, obviously there is a run-time-error. Since "I am a const!" is a const char*, why the compiler doesn't give an error or even a warning ??
Besides, if I define char a[] = "I am const!"
, all the elements in a
can be modified, why this time the string literals become nonconst
?
As far as C is concerned, that string literal is not const, it's a char[14]
which you assign to a char*, which is perfectly fine.
However, C does say that changing a string literal is undefined behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With