問(wèn)題描述
我知道const char *
是一個(gè)指向const char 的指針,而char *const
是一個(gè)指向char 的常量指針.我正在以下代碼中對(duì)此進(jìn)行測(cè)試:
I know that const char *
is a pointer to a const char, while char *const
is a constant pointer to a char.
I am testing this in the following code:
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?
最后一行沒(méi)有給出任何錯(cuò)誤,而是導(dǎo)致程序意外終止.為什么不允許修改t
指向的字符串?
The last line does not give any error, but causes the program to terminate unexpectedly. Why is modifying the string pointed to by t
not allowed?
推薦答案
t
指向一個(gè)字符串文字 修改字符串文字是未定義的行為.C++ 草案標(biāo)準(zhǔn)部分 2.14.5
String literals 段落 12 說(shuō)(強(qiáng)調(diào)我的):
t
is pointing to a string literal it is undefined behavior to modify a string literal. The C++ draft standard section 2.14.5
String literals paragraph 12 says(emphasis mine):
是否所有字符串文字都是不同的(即存儲(chǔ)在非重疊對(duì)象中)是實(shí)現(xiàn)定義的.嘗試修改字符串文字的效果未定義.
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 草案標(biāo)準(zhǔn)的相關(guān)部分是 6.4.5
String literals 段落 6 說(shuō)(強(qiáng)調(diào)我的em>):
The relevant section from the C99 draft standard is 6.4.5
String literals paragraph 6 which says(emphasis mine):
未指定這些數(shù)組是否不同,前提是它們的元素具有適當(dāng)?shù)闹?如果程序試圖修改這樣的數(shù)組,行為是未定義.
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.
在典型的現(xiàn)代 Unix 平臺(tái)上,您會(huì)在只讀段中找到字符串文字,如果我們嘗試修改它,這將導(dǎo)致訪問(wèn)沖突.我們可以使用 objdump 來(lái)檢查只讀部分,如下所示:
On a typical modern Unix platform you will find string literals in the read-only segment which would result in a access violation if we attempt to modify it. We can use objdump to inspect the read-only section as follows:
objdump -s -j .rodata
我們可以在下面的實(shí)際示例中看到確實(shí)會(huì)找到字符串文字在只讀部分.請(qǐng)注意,我必須添加一個(gè) printf
否則編譯器會(huì)優(yōu)化出字符串文字.示例 `objdump 輸出:
we can see in the following live example that the string literal will indeed be found in the read-only section. Note that I had to add a printf
otherwise the compiler would optimize out the string literal. Sample `objdump output:
Contents of section .rodata:
400668 01000200 776f726c 64002573 0a00 ....world.%s..
另一種方法是讓 t
指向一個(gè)帶有 字符串文字 副本的數(shù)組,如下所示:
An alternative approach would be to have t
point to an array with a copy of a string literal like so:
char r[] = "world";
char *const t = r ;
這篇關(guān)于修改 char *const 字符串的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!