为什么写入“char *s"时会出现分段错误?用字符串文字初始化,但不是“char s[]"? [英] Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"?

查看:11
本文介绍了为什么写入“char *s"时会出现分段错误?用字符串文字初始化,但不是“char s[]"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The following code receives seg fault on line 2:

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

虽然效果很好:

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

通过 MSVC 和 GCC 测试.

Tested with MSVC and GCC.

推荐答案

参见 C 常见问题,问题1.32

:这些初始化有什么区别?
char a[] = "字符串字面量";
char *p = "字符串字面量";
如果我尝试为 p[i].

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:字符串文字(正式术语对于 C 中的双引号字符串源)可以用在两个咯不同的方式:

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

  1. 作为 char 数组的初始化器,就像在 char a[] 的声明中一样,它指定了初始值该数组中的字符数(并且,如有必要,它的大小).
  2. 在其他任何地方,它都会变成一个未命名的静态字符数组,并且可以存储这个未命名的数组在只读存储器中,其中因此不一定是修改的.在表达式上下文中,数组立即转换为指针,像往常一样(见第 6 节),所以第二个声明初始化 p指向未命名数组的第一个元素.
  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.

一些编译器有一个开关控制是否为字符串文字是否可写(用于编译旧的代码),有些可能有选项使字符串文字正式视为 const char 的数组(对于更好的错误捕获).

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

这篇关于为什么写入“char *s"时会出现分段错误?用字符串文字初始化,但不是“char s[]"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆