内存中的文字究竟在哪里?(见下面的例子)
我不能修改文字,所以它应该是一个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 …Run Code Online (Sandbox Code Playgroud) 假设有以下两段代码:
char *c = "hello world";
c[1] = 'y';
Run Code Online (Sandbox Code Playgroud)
上面那个不行。
char c[] = "hello world";
c[1] = 'y';
Run Code Online (Sandbox Code Playgroud)
这个可以。
关于第一个,我知道字符串“hello world”可能存储在只读内存部分,因此无法更改。然而,第二个在堆栈上创建一个字符数组,因此可以修改。
我的问题是 - 为什么编译器不检测到第一种类型的错误?为什么这不是 C 标准的一部分?这有什么特殊原因吗?