数组和指针的区别,以字符串 [英] Difference between array and pointer to string literal
问题描述
我是新来的 C 的,所以它可能是一个愚蠢的问题。我写了一块code像波纹管:
I am new to C, so it may be a dumb question. I was writing a piece of code like bellow:
char ar[]="test";
*(ar+1)='r';
这是工作的罚款。但每当我这样做:
this is working fine. But whenever I am doing it:
char *p="test";
*(p+1)="r";
这是给人的分段故障的。任何人都可以请为什么第二种情况是给段错误描述?但从记忆点的解释将是AP preciated。
this is giving segmentation fault. Can anyone please describe why second case is giving segmentation fault? explanation from memory point of view will be appreciated.
推荐答案
在第二种情况下 P
指向一个的字符串的你不允许修改的字符串的,它是未定义行为。从 C99标准草案部分 6.4.5
的字符串字面的段落的 6 的(重点煤矿的):
In the second case p
is pointing to a string literal and you are not allowed to modify a string literal, it is undefined behavior. From the C99 draft standard section 6.4.5
String literals paragraph 6 (emphasis mine):
这是不确定的,这些阵列是否提供了不同的元素都在
适当的值。 如果该程序试图修改这样的阵列,该行为是
未定义
It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.
在第一种情况下 AR
是一个自动变量,你可以修改它,因为它没有的常量的资格。的内容的字符串的初始化期间被复制或 AR
。
In the first case ar
is an automatic variable and you are allowed to modify it since it not const qualified. The contents of the string literal are being copied during initialization or ar
.
这篇关于数组和指针的区别,以字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!