char *str vs char str[] : segmentation issue [duplicate]

╄→гoц情女王★ 提交于 2021-01-29 11:13:45

问题


#include <stdio.h>
#include <conio.h>

void test(char *p)
{
     p = p + 1;
     *p = 'a';
}

int main()
{
    char *str = "Hello";
    test(str);
    printf("%s", str);
    getch();
    return 0;
}

When I run this code it gives segmentation error ? why is this happening. The const theory is not clear to me... whereas if I declare str as char str[], it does the job. Are they not both basically the same things ?


回答1:


str is pointing to a string literal, you are attempting to modify the string literal in the function test on this line:

*p = 'a';

It is undefined behavior to attempt to modify a string literal. You can alternatively, make a copy of the string literal into a array as follows:

char str[] = "Hello";

now it is perfectly ok to modify str. From the draft C99 standard, under section 6.4.5 String literals paragraph 6:

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.




回答2:


*p = 'a';

The problem is the above statement tries to modify the read only segment. String literal "Hello" resides in read only segment and can not be modified.

char str[] = "Hello";

The above statement copies Hello to str character array and the array contents can be modified.



来源:https://stackoverflow.com/questions/18215001/char-str-vs-char-str-segmentation-issue

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