Difference between array and pointer to string literal

邮差的信 提交于 2019-12-12 14:01:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!