2011-07-16 36 views
2

Possible Duplicate:
C/C++ Char Pointer Crash爲什麼增加指針崩潰指向的數據?

char *p = "atl"; 
char c; 
c = ++*p; //crashing here 

爲什麼崩潰?

我知道內存不是爲指針增量創建的,應該在數據上完成。

+0

這個問題已被問了很多很多次之前:http://stackoverflow.com/questions/4226829/cc-char-pointer-crash http://stackoverflow.com/questions/2437318/why-does-this -code-crash http://stackoverflow.com/questions/5972915/string-constants-vs-char-arrays-in-c http://stackoverflow.com/questions/5142988/c-pointer-arithmetic-on-characters http://stackoverflow.com/questions/3090610/c-char-pointer-problem僅舉幾例 –

回答

8

p指向const數據是字符串文字"atl";這意味着,*p無法更改。但是您正在嘗試通過編寫++*p來更改它。這就是它在運行時崩潰的原因。

事實上,大多數編譯器會在編寫char *p ="atl"時發出警告。你應該寫:

const char *p ="atl"; 

如果你寫的話,那麼當你在編譯的時候自己寫++*p編譯器會給出錯誤。在編譯時檢測錯誤比在運行時檢測錯誤要好。看到這裏的編譯錯誤現在:

的編譯錯誤是:

prog.cpp:7: error: increment of read-only location ‘* p’


但是,如果你寫

char p[] = "atl"; 
char c = ++*p; //ok 

那麼現在它的正確。因爲現在p是一個數組,它是由字符串文字"atl"創建的。它不再指向字符串文字本身了。所以你可以改變數組的內容。

+0

char str1 [] = {'s','o','m','e'}; char str2 [] = {'s','o','m','e','\ 0'}; char * p = str1; char c = ++ * p;是不是程序不同?(它不是崩潰) – Suri

+1

謝謝,我明白了這一點 – Suri

相關問題