内存中的文字到底在哪里? (参见下面的示例)
我无法修改文字,因此它应该是 const char*,尽管编译器允许我使用 char*,但即使使用大多数编译器标志,我也没有警告。
虽然 const char* 类型到 char* 类型的隐式转换给了我一个警告,请参见下文(在 GCC 上测试,但在 VC++2010 上的行为类似)。
此外,如果我修改 const char 的值(使用下面的技巧,GCC 最好给我一个警告),它不会给出错误,我什至可以在 GCC 上修改和显示它(即使我猜它是这样的)仍然是一个未定义的行为,我想知道为什么它没有对文字做同样的事情)。这就是为什么我要问这些文字存储在哪里,以及更常见的 const 应该存储在哪里?
const char* a = "test";
char* b = a; /* warning: initialization discards qualifiers
from pointer target type (on gcc), error on VC++2k10 */
char *c = "test"; // no compile errors
c[0] = 'p'; /* bus error when execution (we are not supposed to
modify const anyway, so why can I and with no errors? And where is the
literal stored for I have a "bus error"?
I have 'access violation writing' on VC++2010 */
const char d = 'a';
*(char*)&d = 'b'; // no warnings (why not?)
printf("%c", d); /* displays 'b' (why doesn't it do the same
behavior as modifying a literal? It displays 'a' on VC++2010 */
最佳答案
C 标准并不禁止修改字符串文字。它只是说如果尝试的话,行为是不确定的。根据C99的基本原理,委员会中有人希望字符串文字是可修改的,因此标准并没有明确禁止它。
请注意,C++ 中的情况有所不同。在 C++ 中,字符串文字是 const char 的数组。但是,C++ 允许从 const char * 到 char * 的转换。不过,该功能已被弃用。
关于c++ - 为什么编译器允许字符串文字不是 const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32807364/