2013-02-19 143 views
0

給出下面的代碼解引用指針的指針

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

註釋的行導致段故障。

有人能解釋一下究竟發生了什麼嗎?

爲什麼該行和下一個打印語句不等效?

感謝

回答

6

> Can some one please explain what is actually happening?

這是一個operation precedence問題:

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

注意額外的括號的[1]之前分組的foo->bar的尊重,你必須這樣做,因爲下標([] )運算符具有比解除引用更高的優先級(*)運算符

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

因爲分手的聲明,你把操作問題的順序照顧,您所做的優先級較低的操作第一次發生:

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

數組索引操作符[]具有更高的優先級比操作符*。因此,該行意味着「在foo->bar陣列的索引1處尊重int *」。但是,當然,您只有一個1 int *(索引0)的數組,因此會導致seg錯誤。