简体   繁体   中英

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"; is read only. Trying to write to it is illegal, and will result in a segmentation fault.

char *x = "Hello";

This declaration makes it read-only. Writing to it the way you tried is illegal.

See this for more information

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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