當你
char wrong[20] = "la1 4yt";
編譯器拷貝字符串的文字{'l', 'a', '1', ' ', '4', 'y', 't', '\0'}
到wrong
陣列的相應元素中的元素;當你做
char *wrong = "la1 4yt";
編譯器分配給wrong
字符串常量的地址。
字符串文字char[]
(字符數組),不const char[]
...但你不能改變他們!從標準
報價:
6.4.5 String literals
6 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.
當我使用一個字符串初始化char *
,我平時也告訴編譯器我不會改變該字符串的內容文字中加入一個const
到定義。
const char *wrong = "la1 4yt";
編輯
假設你有
char *test1 = "example test";
char *test2 = "test";
,編譯器創建1單一字符串字面量和使用的單一字符串文字來初始化TEST1和TEST2。如果你被允許改變字符串字面...
test1[10] = 'x'; /* attempt to change the 's' */
printf("%s\n", test2); /* print "text", not "test"! */
來源
2009-10-30 00:23:28
pmg
http://stackoverflow.com/questions/1614723/why-is-this-c-code-causing-a-segmentation-fault/1614739#1614739 – AnT 2009-10-30 00:29:47
+1避免'* postcode = toupper(* postcode ++) ;''或同樣不好的'*郵編++ = toupper(*郵編);':) – pmg 2009-10-30 00:55:31
爲了大聲哭泣......這個問題每週至少會彈出兩次。 – ephemient 2009-10-30 01:03:48