2014-12-01 83 views
1
struct node 
{ 
    int data; 
    struct node *next; 
}*head; 

爲什麼我們有* head?而這是不是做在C中聲明結構

typedef struct 
{ 
    int data; 
    struct node *next; 
}head; 
+0

我認爲這是一個「風格」的感覺更好。我的意思是,「節點」將在可能的「TAD」用這樣的「頭」(通常是同時處理列表)需要作爲一個指針,所以你在定義結構節點時聲明它,而不是稍後在代碼中明確地聲明它。 – FacundoGFlores 2014-12-01 19:52:28

回答

3

第一部分定義變量head,它是指向struct node類型的指針。它可以是NULL,表明你的鏈表有零個元素。

第二個塊只是聲明瞭一個叫做head的類型。這根本不是一個變量。並且它不會編譯爲其next字段的類型,struct node不存在。

你可能想

typedef struct node { 
    int data; 
    struct node *next; 
} node; 
node *head; 

這種形式宣佈2種類型,struct nodenode(下同),並定義一個變量head。我會去第一個沒有typedef的表單,因爲它更簡單,而且無論如何你都不能在結構的next字段中引用typedef。

2

第一個版本聲明瞭一個類型(struct node)不同(更好?),以及可變head這是一個指向struct node。所有列表都需要一個頭,所以這很有幫助。

第二個聲明head作爲(否則未命名)struct的類型名稱。它不會實際編譯,因爲內部的struct node *next引用了一個不存在的類型。

0

在第一個示例中,您定義了struct,但還聲明瞭head變量是指向此類struct的指針。

在你的第二個例子(typedef),你只需要聲明某種類型的同義詞(但 沒有變量!)

0
struct node 
{ 
    int data; 
    struct node *next; 
}*head; 
在你上面有申報對象頭指針代碼

所以才能訪問其元素您需要使用的數據 - >運算符,例如head-> data = 4;等

您可以創建節點追加頭指針

typedef struct 
{ 
    int data; 
    struct node *next; 
}head; 

在此as這種代碼,您創建將成爲頭的類型,將創建一個問題,當你刪除,如果頭節點每個節點你寫的鏈表代碼刪除頭你無法重新定義新的頭部

,其中在前面的代碼頭是一個指針可以通過更新後的頭戴式在更新其結構下一個元素是改變>未來在前面的代碼中,我們可以輕鬆刪除以前的頭部而不會丟失新頭

0
the gdb debugger (and perhaps other debuggers) 
can only see the contents/format of a struct that contains a tag name. 

The use of a typedef hides the tag name and defines a new type. 
however, gdb will not properly display the contents of any instance of the struct. 

The correct way is: 
struct tagname { ... }; 

Notice no struct name to clutter the symbol table and create confusion 
Of course, then each defining instance of this struct needs to be written as: 
struct tagname myName; 
but that should not be a problem and adds the visible documentation 
that myName is a struct 

Along with the increased visibility of the struct, both to gdb and the reader 
of the resulting code, any pointer to that struct should never be defined 
as part of the struct definition. Such a formatting hides the 
fact that such name is a pointer. rather declare an instance of a pointer as: 
struct tagname * pMyStruct; 

And, never use this syntax: 
struct { ... } structName; 
as that is a depreciated syntax