2017-04-18 89 views
0

給出的示例是雙向鏈表的代碼的一部分。 可以說,我有以下兩個給定typedefs的結構。成員使用指針訪問嵌套結構。箭頭運算符相當於

typedef struct dplist dplist_t; 
typedef struct dplist_node dplist_node_t; 

struct dplist_node { 
    dplist_node_t * prev, * next; 
    element_t element; 
}; 

struct dplist { 
    dplist_node_t * head; 
}; 

而且我在我的主要功能如下代碼:

void main() 
{ 
    dplist_t * list; 
    dplist_node_t *node_one, *node_two; 

    //the arrow equivalent of the assignment 
    list->head = node_one; 
    list->head->next = node_two; 
} 

我知道node_one分配的「點」相當於是:

(*list).head = node_one; 

但是當我嘗試找到node_two賦值的「點」相當於下列所有變體似乎是錯誤的:

(*list).(*head).next = node_two; 
(*list).*head.next = node_two; 
(*list).head.next = node_two; 

有沒有人知道寫這句話的正確方法?

+4

'(*(* list).head).next = node_two;'。 – willys

+0

因爲head指向node_one而node_one是未初始化的指針,所以你應該調用'list-> head-> next = node_two;'來獲得段錯誤。 – Rogus

+1

@羅格斯這僅僅是一個例子,我只是很快寫出來,沒有編譯或者任何東西來顯示問題背後的想法。 – TheAlPaca02

回答

1

list->head->next = node_two;可以寫成

(*(list->head)).next = node_two; 

其可以被重新寫爲

(*((*list).head)).next = node_two; 
+0

爲什麼需要在第二行中使用雙括號? (在* list.head的雙對中,我根據@willys的回答在我原來的問題的評論中進行了測試,並且這似乎也很好地工作。 – TheAlPaca02

+1

@ TheAlPaca02;這只是爲了清楚。 – haccks

1

應該是 「(*(*列表)。頭)的.next = node_two;」。

。我假設你故意錯過了爲列表/節點分配內存的行(list = malloc(...)),以便使問題簡短化。

。使用 」。」指示編譯器以已知位置/偏移量的偏移量到達數據成員,「 - >」指示運行時需要的取消引用(用於指針)。因此,邏輯將不得不 「列表」(*列表)的)

一個)解除引用地址,

b)計算偏移到部件 「頭」(*列表)。頭,

Ç *((* list).head)的解引用地址,

d)計算成員偏移量「next」*((* list).head).next。