当你
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