为什么 scanf 看起来像是改变了 char* 的行为?

问题描述 投票:0回答:1

我有以下代码,我发现很难理解它为什么会这样工作:

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 的指针,我想知道它如何作为字符串工作以某种方式。但我想知道为什么第一个按预期作为字符数组工作,而不是第二个。

谢谢。

c scanf
1个回答
2
投票

scanf("%s",&str);
调用未定义的行为:您要求
scanf
读取字符串并将其存储到
str
指针本身的位置,而不是它指向的位置,后者是也不应该修改的字符串文字。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.