#include<stdio.h>
int main(void)
{
char * p= "strings are good";
printf("%s",*p);
return 0;
}
有人能告诉我为什么会出现段错误吗?
最佳答案
Could somebody please tell me why I am getting segmentation fault here?
C11: 7.21.6 格式化输入/输出函数:
If a conversion specification is invalid, the behavior is undefined.282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
3.4.3
1 undefined behavior behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements.
2 NOTE Possible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).
*p
是 char
类型。 %s
需要类型为 char *
的参数。这将调用未定义的行为。在这种情况下,任何事情都可能发生。有时您可能会得到预期的结果,有时则不会。这也可能导致程序崩溃或段错误(这里就是这种情况)。
对于%s
,您需要传递字符串/文字的起始地址。
改变
printf("%s",*p);
到
printf("%s",p);
关于c - 引用 char 数组时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20633175/