开发者

Why the following will produce segmentation fault?

int main()
{
        char *temp = "Paras";

        int i;
        i=0;

        temp[3]='F';

        for (i =0 ; i < 5 ; i++ )
                printf("%c\n", temp[i]);

        return 0;
}

Why temp[3]='F'; will cause segmentation fault sinc开发者_Go百科e temp is not const?


You are not allowed to modify string literals.


*temp is defined as a pointer to a constant (sometimes called a string literal - especially in other languages).

Therefore the line with the error is trying to change the third character of this constant.

Try defining a char array and using strcpy to copy temp into it. Then do the above code on the array, it should work. (sorry my ipad here doesn't like to insert code into SO's interface)


As you can see, temp is a pointer, which points to a random address where the nameless array with the value Paras resides. And that array is a string constant.

For your program to work, you need to use an array instead of a pointer:

char temp[6] = "Paras";

Now if you're wondering why it's temp[6] instead of temp[5], the above code initializes a string, and completely different from:

char temp[5] = {'P', 'a', 'r', 'a', 's'};

Strings are terminated with a null terminator \0. And the string initialization will be like:

char temp[6] = {'P', 'a', 'r', 'a', 's', '\0'};


  temp[3]='F'; 

This line is not correct.The "temp" is const value,So you can't modify it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜