sprintf崩溃,但目前还不清楚为什么

时间:2016-10-13 13:40:56

标签: c printf

我使用sprintf尝试了以下代码,但在某些情况下崩溃并在另一种情况下正常工作。有人能解释一下吗?

#include <stdio.h>
#include <stdlib.h>
int main()
{
       //char *s = malloc(20); //works fine
       //char *s = "";         //does not work, no matter what the initial value is
       char s[20];       //works fine
       sprintf(s, "%s", "hello world");
       printf("%s",s);
       return 0;
}

1 个答案:

答案 0 :(得分:3)

当你这样做时:

char *s = "";

char *s = "longer string";

您正在创建一个可能放在只读内存中的文字字符串。所以你以后无法改变

如果您尝试执行以下语法:

char s[] = "...";

数组将使用文字字符串进行初始化,您可以稍后修改原始数组。

网站上的建议问题:

  1. What is the difference between char s[] and char *s in C?
  2. Why do I get a segmentation fault when writing to a string initialized with “char *s” but not “char s[]”?
相关问题