c - 为什么 scanf 看起来会改变 char* 的行为?

标签 c scanf

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

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 的位置 指针本身,而不是它指向的位置,它是一个字符串文字,也不应该被修改。

关于c - 为什么 scanf 看起来会改变 char* 的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40392294/

相关文章:

Java Base64 编码给出与 C base64 编码不同的结果

c - 递归函数在C中返回0

Char(单个字母)必须是一个指针才能正常工作?

c - 这个 MPI 代码有什么问题?

c - Scanf 似乎无法在带有 GDB 的 Eclipse CDT 中以 Debug模式工作

php - 如何使用 fscanf 读取整行(字符串)?

c - 为什么我需要设置比实际大小更大的堆栈大小?

c - 简单的 C 菜单构建,Scanf 不拖拉输入

c - 一个简单的程序有些奇怪,可能是 scanf 问题

C : How to check end of input from keyboard or file while using scanf one char at a time