0

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;
}

2 Answers 2

4

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].

Sign up to request clarification or add additional context in comments.

4 Comments

Why do I have the feeling that you are a high reputation user who has created a new account? :)
Is there a benefit to smurfing accounts on SO?
thanks. now i know why it not works and got working code. :)
@machine_1: I don't know, but I haven't.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.