简体   繁体   中英

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

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

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.

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