#include <stdio.h>
int main()
{
char str[11] = "HelloWorld";
printf("%s\n",str);
printf("%s\n",str+3);
/* This Line here is the devil */
printf("%s\n",str[2]); // %s needs an addr not a value.
return 0;
}
为什么该行会出现段错误。是不是因为 printf
中的 %s
需要地址而不是值。
真正的原因是什么??
最佳答案
str[2]
返回一个字符,而不是指向字符的指针。因此,printf
将尝试从地址 0x6c
开始读取。就在那里,很有可能 0x6c
是一个会导致段错误的无效地址。但是,如果它不是无效的,则 printf
将继续读取直到它到达 0x00
字符,这很可能会进入无效的地址范围。
如果您想确切地知道它为什么会出现段错误,您需要在调试器中进行操作,这可能很有趣并且很有教育意义。
如果您想修复崩溃行,您可以将其更改为:
printf("%s\n", &str[2]);
我认为这是比 str+2
更好的样式。
关于c - printf 中的 %s 格式说明符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13666593/