为什么在写入“ 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[]"?

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

问题描述

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

The following code receives seg fault on line 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测试。

Tested with MSVC and GCC.

推荐答案

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

See the C FAQ, Question 1.32


Q :这些初始化之间有什么区别?

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. 在其他任何地方,它将变成一个未命名的静态数组性格s,
    和此未命名数组可以将
    存储在只读存储器中,因此不必对
    进行修改。在表达式上下文中,数组
    像通常一样立即转换为
    指针(请参见第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天全站免登陆