2015-09-24 49 views
0

我是新来的指针,有这种代码合并排序的链接列表。在这里它已经声明一个虚拟节点为struct node dummy;,虚拟节点的下一个节点为NULL,所以要设置它我们使用dummy.next = NULL;struct node和struct node *之间的' - >'有什么区别?

/* Link list node */ 
struct node 
{ 
    int data; 
    struct node* next; 
}; 
struct node* SortedMerge(struct node* a, struct node* b) 
{ 
    /* a dummy first node to hang the result on */ 
    struct node dummy;  

    /* tail points to the last result node */ 
    struct node* tail = &dummy; 

    /* so tail->next is the place to add new nodes 
    to the result. */ 
    dummy.next = NULL; 
//Code continues... 
} 

我知道我可以使用它,如果它是struct node *dummy; ,但因为它不是一个指针节点,我们不能在这里使用它。 所以我的问题是为什么dummy->next = NULL在这里工作? 和struct node和struct node *之间的区别是什么?

+3

虚拟不是一个指针,所以' - >'不起作用。 ' - >'仅用于指针。 – juanchopanza

+0

所以基本上你会问指针和普通变量之间的区别吗? – ameyCU

回答

3

a -> b(*a).b的简写。

如果a不是指针,则*a无效,也不是a -> b

1

我知道我可以使用它,如果它是struct node *dummy;

如果“它”你的意思struct node dummy;那么答案是否定的。与指向node的指针相同,不能使用指向node的指针。

所以我的问题是为什么不dummy->next = NULL在这里工作?

dummy由于是node,而不是一个指针,和操作员->如果指针。表达式dummy->next具有与(*dummy).next相同的语义。

1

。所以我的问题是为什么dummy-> next = NULL在这里工作?和struct node和struct node *有什么区别?

声明为此struct node dummy;

dummy->next=NULL不起作用,因为dummy不是指向struct。

如果你写了这么 -

struct node A; // then A is a struct variable which can access struct members using '.' operator 

这 -

struct node* B; // then B is a pointer to struct node which can access struct member using '->` or like this (*B).data=something. 
2

dummy不是指向结构的指针。它本身就是结构变量。 只有当它是一个指向结构的指针时,才可以使用运算符->取消结构的属性。

如果您使用的是struct变量,那么.就是要走的路,这与dummy的情况非常相似。

相关问题