问题
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";
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.
回答1:
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.
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
.
回答2:
In a c , whenever u store a string in an array, you could allow to change the content of the string . the reason for this, c store the content of string in a consecutive memory.
In the case of pointer , the pointer stored the starting address of the string and it assumes that would be constant . suppose , you try to change it. you get an undefined behavior , even the worse case is , you cant find it easily just because it wont be throw any error regarding this.
回答3:
the other aspect of your example 'r' == 114 (probably), while "r" == the address of the start of the const string "r" in your executable
来源:https://stackoverflow.com/questions/20296674/difference-between-array-and-pointer-to-string-literal