c - 为什么在写入使用字符串文字初始化的 "char *s"而不是 "char s[]"时出现段错误?

标签 c segmentation-fault c-strings

以下代码在第 2 行收到段错误:

char *str = "string";
str[0] = 'z';  // could be also written as *str = 'z'
printf("%s\n", str);

虽然这非常有效:

char str[] = "string";
str[0] = 'z';
printf("%s\n", str);

使用 MSVC 和 GCC 测试。

最佳答案

请参阅 C 常见问题解答,Question 1.32

Q: What is the difference between these initializations?
char a[] = "string literal";
char *p = "string literal";
My program crashes if I try to assign a new value to p[i].

A: A string literal (the formal term for a double-quoted string in C source) can be used in two slightly different ways:

  1. As the initializer for an array of char, as in the declaration of char a[] , it specifies the initial values of the characters in that array (and, if necessary, its size).
  2. Anywhere else, it turns into an unnamed, static array of characters, and this unnamed array may be stored in read-only memory, and which therefore cannot necessarily be modified. In an expression context, the array is converted at once to a pointer, as usual (see section 6), so the second declaration initializes p to point to the unnamed array's first element.

Some compilers have a switch controlling whether string literals are writable or not (for compiling old code), and some may have options to cause string literals to be formally treated as arrays of const char (for better error catching).

关于c - 为什么在写入使用字符串文字初始化的 "char *s"而不是 "char s[]"时出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/164194/

相关文章:

C++:在被本地字符串捕获后释放或销毁 malloc 的 char *?

c - 确定主线程 pthread_create 中的参数在 C 中是否为 NULL

c - EPOLLERR 和 EPOLLHUP 的真正含义是什么以及如何处理它们?

c++ - 树实现给出段错误(核心转储)错误 c++ 11

c - C 字符串的空终止

c - 如何从给定索引strcat和strcpy一个字符串?

c++ - 菜单项是单选样式,而不是MF_CHECKED?

c - 线程改变堆内存

c - malloc : is first 'out of bounds' value always NULL/0? 的行为

python - 单线程 C 程序中 Py_Finalize (python 2.5) 的段错误