2011-06-17 33 views
3

我找回成C++,並有指針和諸如此類的東西的竅門,但是,我希望我能得到一些幫助理解爲什麼這個代碼段中給出了一個總線錯誤。需要幫助的字符改變單個字符*

char * str1 = "Hello World"; 
*str1 = '5'; 

錯誤:總線錯誤:(

更普遍,我想知道如何改變單一字符的值在一個CString因爲我的理解是,*海峽=「5」應該改變。該值STR分從「H」到「5」,所以,如果我是打印出的STR它會讀:「5ello世界」

在試圖理解我寫了這個代碼片斷太,其中工程如預期;

char test2[] = "Hello World"; 
char *testpa2 = &test2[0]; 
*testpa2 = '5'; 

這給出了所需的輸出。那麼testpa2和str1有什麼區別?難道他們都不指向一系列以空字符結尾的字符?

回答

5

當你說char *str = "Hello World";你正在指向一個文本字符串是不可改變的。應該要求將文字分配給const char*,但由於歷史原因,情況並非如此(oops)。

當你說char str[] = "Hello World;"你正在創建一個數組,它被初始化爲(在編譯時已知的字符串)。這是可以修改的。

+0

真棒定義。這爲我清除了一切。謝謝! – nick 2011-06-17 02:13:05

4

並非如此簡單。 :-)

第一個創建一個指針到給定的字符串文字,它允許放在只讀存儲器中。

第二個創建一個數組(在堆棧上,通常,因此是讀寫),它被初始化爲給定字符串文本的內容。

3

在您嘗試修改字符串文字的第一個例子,這會導致不確定的行爲。

按照語言標準2.13.4.2

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.

在第二個例子中,你使用的字符串字面初始化,在8.5.2.1

A char array (whether plain char, signed char, or unsigned char) can be initialized by a string- literal (optionally enclosed in braces); a wchar_t array can be initialized by a wide string-literal (option- ally enclosed in braces); successive characters of the string-literal initialize the members of the array.