我知道 const char *
是指向 const char 的指针,而 char *const
是指向 char 的常量指针。
我正在用以下代码对此进行测试:
const char *s = "hello"; // Not permitted to modify the string "hello"
char *const t = "world"; // Not permitted to modify the pointer t
s = "hello2"; // Valid
// t = "world2"; // Invalid, gives compilation error
// *(s + 1) = 'a'; // Invalid, gives compilation error
*(t + 1) = 'a'; // Why does this not work?
最后一行没有给出任何错误,但导致程序意外终止。为什么不允许修改t
指向的字符串?
最佳答案
t
指向一个字符串文字 修改字符串文字 是未定义的行为。 C++ 草案标准部分 2.14.5
String literals 段落 12 说(强调我的):
Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation defined. The effect of attempting to modify a string literal is undefined.
C99 标准草案的相关部分是 6.4.5
String literals paragraph 6 说(强调我的 em>):
It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
在典型的现代 Unix 平台上,您会在只读段中找到字符串文字,如果我们尝试修改它,将导致访问冲突。我们可以使用 objdump 来检查只读部分,如下所示:
objdump -s -j .rodata
我们可以在下面看到live example字符串文字确实会在只读 部分中找到。请注意,我必须添加 printf
否则编译器会优化掉字符串文字。示例`objdump 输出:
Contents of section .rodata:
400668 01000200 776f726c 64002573 0a00 ....world.%s..
另一种方法是让 t
指向一个包含 string literal 拷贝的数组,如下所示:
char r[] = "world";
char *const t = r ;
关于c++ - 修改 char *const 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19372952/