我有以下代码,我发现很难理解它为什么会这样工作:
char* str = "HELLO";
printf("%s",&str[0]); //Returns Hello as expected
printf("%c",str[2]); //Returns L as aspected
scanf("%s",&str); //I enter aaaa
printf("%s\n",&str); /* If I want to access the word I have to do this way
&str[0] now gives a segmentation fault.*/
printf("%c\n",&str[1]); /*This gives a b???!!!. I haven't found any way to
access individual character with *str.*/
我特别感兴趣的是为什么看起来无法访问单个字符,尽管在某种程度上这是有道理的,毕竟你应该声明一个指向 char 的指针,我想知道它如何作为字符串工作以某种方式。但我想知道为什么第一个按预期作为字符数组工作,而不是第二个。
谢谢。
scanf("%s",&str);
调用未定义的行为:您要求 scanf
读取字符串并将其存储到 str
指针本身的位置,而不是它指向的位置,后者是也不应该修改的字符串文字。