2015-09-24 335 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的情況非常相似。

相關問題