2016-01-12 332 views
-1
#include<stdio.h> 
#include<stdlib.h> 
struct test 
{ 
    int data; 
    struct test *next; 
}; 
void main() 
{ 

    struct test *head=(struct test *)malloc(sizeof(struct test)); 
    struct test **ref=&head; 

    head->data=5; 
    head->next=NULL; 
    printf("\n %d \n %d",head->data,head->next); 
    printf("\n %d \n %d",**ref->data,**ref->next); 



} 

說明:C指針雙指針

我已經試過上述一段代碼。

是不是**ref是否與*head相同?如果不是爲什麼?

此外,編譯器在第二printf引發錯誤說datanext不是structureunion的一部分。

+1

歡迎來到Stack Overflow! [請參閱此討論,爲什麼不在'C'中投射'malloc()'和family的返回值。](http://stackoverflow.com/q/605845/2173917)。 –

+1

沒有任何編程方面,如果'** ref與* head'相同,那麼爲什麼你認爲額外的'*'在那裏呢? –

+0

換句話說,在你的'printf(「\ n%d \ n%p」,(* ref) - > data,(* ref) - > next)版本中有''''和'您需要將圓括號內的指針包圍起來,才能應用正確的運算符優先級。 –

回答

3

你有兩個錯誤,一個語法(當你使用點符號時使用箭頭符號),另一個與operator precedence有關。

選擇運算符->.比取消引用運算符*具有更高的優先級。這意味着表達式**ref->data等於**(ref->data)。這當然是無稽之談,不會構建爲data不是一個指針。

你有兩個選擇:

  1. 使用例如(*ref)->data
  2. 使用例如(**ref).data

我會選擇去1作爲ref「參考」一指針的結構,即語法更內嵌你做什麼,IMO。


在一個不相關的音符,你不應該打印指針時,你應該使用"%p"使用"%d"格式。見例如this printf (and family) reference

1

**ref是指向指向struct test的指針,*head是指向struct test的指針。

誤差是存在的,因爲whene參考,**refstruct test類型的,你應該使用點.去的結構的成員:

(**ref).data 

head是一個指向struct test,和您可以在那裏正確使用->運算符。