c - 引用 char 数组时出现段错误

标签 c arrays char segmentation-fault

#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).

*pchar 类型。 %s 需要类型为 char * 的参数。这将调用未定义的行为。在这种情况下,任何事情都可能发生。有时您可能会得到预期的结果,有时则不会。这也可能导致程序崩溃或段错误(这里就是这种情况)。

对于%s,您需要传递字符串/文字的起始地址。

改变

printf("%s",*p);  

printf("%s",p);

关于c - 引用 char 数组时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20633175/

相关文章:

Android NDK设置RGB位图像素

javascript - 排名数字数组值

C:将 token 存储在不断增长的数组中

java - 带有字符和ascii值的开关大小写在java中表现相同

c - 反向保存字符串

在 C 中访问零长度数组的地址时出现编译错误

c - 尝试使用字符串比较对链表进行排序时出错

php - 如果我需要这些键同时具有值​​(从数据库传递),如何将键添加到 PHP 数组?

c++ - 为什么我不需要取消引用 char 指针来输出 c 风格的字符串?

java - Java NIO中ByteBuffer和CharBuffer有什么区别?