为什么“char*”是可以指向“const char*”吗?
下面的代码在 VC 或 gcc 上都可以正确编译:
char *str = "I am a const!";
str[2] = 'n';
但是,显然存在运行时错误。因为“我是一个常量!”是一个const char*,为什么编译器不给出错误甚至警告?
另外,如果我定义了 char a[] = "I am const!"
,那么 a
中的所有元素都可以修改,为什么这次字符串文字变成了 非常量?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就 C 而言,该字符串文字不是 const,它是一个 char[14],您可以将其分配给 char*,这完全没问题。
然而,C 确实表示更改字符串文字是未定义的行为。
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.