繁体   English   中英

将指针解引用为指针

[英]dereferencing pointer to a pointer

给定以下代码

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

注释掉的行会导致分段错误。

有人可以解释一下实际情况吗?

为什么该行与下一个打印语句不相等?

谢谢

> Can some one please explain what is actually happening?

这是一个操作优先级问题:

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

请注意,额外的括号将[1]之前的foo->barfoo->bar分组,您需要这样做,因为下标( [] )运算符的优先级高于解引用( * )运算符

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

因为通过分解语句来解决操作顺序问题,所以使优先级较低的操作首先发生:

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

数组索引运算符[]的优先级高于deference *运算符。 因此,该行的意思是“在foo->bar数组的索引1处foo->bar int * ”。 但是,当然,您只有1个int * (索引0)的数组,因此会导致段错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM