简体   繁体   English

为什么以下会产生分段错误?

[英]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'; 为什么temp[3]='F'; will cause segmentation fault since temp is not const ? 因为temp不是const会导致分段错误?

您不能修改字符串文字。

*temp is defined as a pointer to a constant (sometimes called a string literal - especially in other languages). * temp被定义为指向常量的指针(有时称为字符串文字 - 特别是在其他语言中)。

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. 尝试定义一个char数组并使用strcpy将temp复制到其中。 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) (对不起,我的ipad在这里不喜欢将代码插入SO的界面)

As you can see, temp is a pointer, which points to a random address where the nameless array with the value Paras resides. 如您所见, temp是一个指针,指向一个随机地址,其中值为Paras的无名数组所在的地址。 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: 现在,如果你想知道为什么它是temp[6]而不是temp[5] ,上面的代码初始化一个字符串,完全不同于:

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

Strings are terminated with a null terminator \\0 . 字符串以null终止符\\0终止。 And the string initialization will be like: 字符串初始化将如下:

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

这行不正确。“temp”是const值,所以你不能修改它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM