Search code examples
cpointersdereference

dereferencing pointer to a pointer


given the following code

#include <stdlib.h>
#include <stdio.h>
typedef struct Foo {
  int **bar;
}Foo;


int main(){
  Foo *foo = malloc(sizeof(Foo));
  foo->bar = malloc(sizeof(int**));
  int *tmp = malloc(sizeof(int)*2);
  tmp[0]= 0;
  tmp[1]=1;
  *(foo->bar) = tmp;
  //printf("%d",*(foo->bar)[1]);  <=== This line                                                                                                                                                                                   
  int *tmp2 = *(foo->bar);
  printf("%d ",tmp2[1]);

  return 0;
}

The line commented out causes a segmentation fault.

Can some one please explain what is actually happening?

Why is that line and the next print statement not equivalent?

Thanks


Solution

  • > Can some one please explain what is actually happening?

    It's an operation precedence problem:

    printf("%d",(*(foo->bar))[1]); // <=== This is what you wanted
    

    Note the extra parens grouping the deference of the foo->bar before the [1], you need to do this because the subscripting ([]) operator has higher precedence than the dereference (*) operator

    > Why is that line and the next print statement not equivalent?

    Because by breaking up the statements you took care of the order of operations issue, you made the lower precedence operation occur first:

    int *tmp2 = *(foo->bar);