2017-04-18 92 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。