Osama Javed
Osama Javed

Reputation: 1442

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

Upvotes: 0

Views: 199

Answers (2)

tom
tom

Reputation: 19153

The array indexing operator [] has a higher precedence than the deference * operator. So, that line means "deference the int * at index 1 of the foo->bar array". But of course, you only have an array of 1 int * (index 0), so a seg fault results.

Upvotes: 2

Mike
Mike

Reputation: 49403

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

Upvotes: 6

Related Questions