开发者

why a "char*" can point to a "const char*"?

开发者 https://www.devze.com 2023-04-10 15:54 出处:网络
the following code can be compiled correctly on both VC or gcc: char *str = \"I am a const!\"; str[2] = \'n\';

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开发者_StackOverflow中文版 "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.

0

精彩评论

暂无评论...
验证码 换一张
取 消