开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜