问题描述
以下代码可以在VC或gcc上正确编译:
char * str =I am a const! ;
str [2] ='n';
然而,显然有一个运行时错误。因为我是一个常数!是一个 const char *,为什么编译器不给出错误或者甚至警告?
此外,如果我定义 char a [] =I am const!
, a
可以修改,为什么这个时候字符串字面值变成 nonconst
解决方案
对于C来说,字符串字面量不是const,它是一个
char [14]
,它分配给一个char *,这是完全正常的。 / p>
但是,C确实说更改字符串文字是未定义的行为。
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.
这篇关于为什么一个“char *”可以指向“const char *”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!