简体   繁体   English

C中的指针到指针引发分段错误

[英]Pointer-to-a-pointer in C throws segmentation fault

This might sound pretty old school, but I'm still unable to figure out why the following program throws a segmentation fault. 这听起来似乎很老,但是我仍然无法弄清楚为什么以下程序会引发分段错误。 Any help would be great 任何帮助都会很棒

#include <stdio.h>
pointer(char **x)
{
    printf ("Before %c",*x[0]);
    *x[0] = 'a';   // segmentation fault here!!
    printf ("After %c", *x[0]);
}
int main()
{
    char *x = "Hello";
    pointer(&x);
}

It's explained in the answer to this question . 对此问题的答案进行了解释。

TL;DR: the memory pointed to by char *x = "Hello"; TL; DR: char *x = "Hello";指向的内存char *x = "Hello"; is read only. 是只读的。 Trying to write to it is illegal, and will result in a segmentation fault. 尝试写入它是非法的,并且会导致分段错误。

char *x = "Hello"; char * x =“ Hello”;

This declaration makes it read-only. 该声明使其为只读。 Writing to it the way you tried is illegal. 以您尝试的方式写给它是非法的。

See this for more information 请参阅以获得更多信息

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

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