[英]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->bar
的foo->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.