简体   繁体   中英

How to fix a print error about an array pointer in C (Segmentation fault)?

I just started learning pointers in C. I found something special and got an error about these code, can you help me find out why the No.9 making "Segmentation fault" error?

#include<stdio.h>

int main() {
    int a[] = {10, 20, 30, 40, 50};
    int *p[] = {a, a+1, a+2, a+3, a+4};
    int **pp = p;
    int ***ppp = &pp;

    printf("\n === Part1 === \n\n");
    printf(" 0. %p\n", a);
    printf(" 1. %p\n", *p);
    printf(" 2. %p\n", *pp);
    printf(" 3. %p\n", **ppp);

    printf("\n === Part2 === \n\n");
    printf(" 4. %d\n", *p[0]);
    printf(" 5. %d\n", *pp[0]);
    printf(" 6. %d\n", **ppp[0]);

    printf("\n === Part3 === \n\n");
    printf(" 7. %d\n", *p[3]);
    printf(" 8. %d\n", *pp[3]);
    printf(" 9. %d\n", **ppp[3]);

    printf("\n");

    return 0;
}

This is to do with operator precedence. [] binds more tightly than * , so **ppp[3] means **(ppp[3]) , which won't do what you want.

I think you want (**ppp)[3] .

Other people have given you what went wrong, this is how to figure it out for next time:

$ gcc -Wall -Werror -std=gnu11 -Wextra -g -O0 -o program program.c
$ gdb ./program
(gdb) run
Program received signal SIGSEGV, Segmentation fault.
main () at program:23
23          printf(" 9. %d\n", **ppp[3]);
(gdb) p ppp[3]
$1 = (int **) 0x7fffffffe2d8
(gdb) p **ppp[3]
Cannot access memory at address 0x280000001e

That shows that trying to dereference *ppp[3] is what caused your segfault. From there, a bit of thinking and playing with it ought to get you to what went wrong. From there to trying a p (**ppp)[3] and seeing that it prints the result you expect shouldn't be too big a step.

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