为什么写有&QUOT初始化字符串时,我得到一个分段错误; char *之S"但不与QUOT;个char [] QUOT ;? [英] Why do I get a segmentation fault when writing to a string initialized with "char *s" but not "char s[]"?

查看:108
本文介绍了为什么写有&QUOT初始化字符串时,我得到一个分段错误; char *之S"但不与QUOT;个char [] QUOT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下code接收第2行赛格故障:

The following code receives seg fault on line 2:

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

虽然这工作得很好:

While this works perfectly well:

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

测试与MSVC和海湾合作委员会。

Tested with MSVC and GCC.

推荐答案

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

See the C FAQ, Question 1.32

问::?什么是这些初始化的区别结果
  一个烧焦[] =字符串; 结果
  的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. 作为初始化的字符数组,如的声明,一个烧焦[] ,它指定的初始值
      该阵列中的字符(和,
      如果需要的话,它的大小)。

  2.   
  3. 在别的地方,它变成一个字符无名,静态数组,
      与此无名阵列可以被存储
      在只读存储器,哪些
      因此可以不必是
      改性。在一个前pression的背景下,
      该阵列被转换可以一次一个
      指针,像往常一样(见第6节),所以
      第二个声明初始化p
      指向无名数组的第一个
      元件。

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

一些编译器有一个开关
  控制是否字符串
  可写或不(编译老
  code),以及一些可能选项
  原因字符串文字被正式
  作为常量字符数组处理(
  更好的错误捕获)。

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

这篇关于为什么写有&QUOT初始化字符串时,我得到一个分段错误; char *之S"但不与QUOT;个char [] QUOT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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