2016-07-22 138 views
4
我使用這個結構鏈表

鏈接列表實現與結構

typedef struct Node{ 
     int value; 
     struct node_t* next; 

}node_t; 

,一切工作正常,直到我把struct node_t* nextint value字段,然後我有很多垃圾值與工作那個結構。 這是關於錯誤的實現或代碼中的其他內容?

+1

在你的代碼'node_t'是一個別名'結構Node'現在。希望有助於理解。 – GergelyPolonkai

+0

請閱讀更新後的答案,你現在明白了嗎? –

回答

4

你在呼喚你的結構Node和定義node_t類型。然後你使用node_t,如果它是結構的名稱,而不是類型。

試試這個

typedef struct node { 
    int value; 
    struct node *next; 
} Node; 

或者

typedef struct node Node; 
struct node { 
    int value; 
    Node *node; 
}; 

如果你把它struct Node,然後

struct Node { 
    int value; 
    /* The compiler doesn't know what `struct Node' is yet */ 
    struct Node *next; 
    /* But you can always declare pointers, even of types the compiler 
    * doesn't know everything about. Because the size of a pointer 
    * does not depend on the type of the pointee. 
    */ 
}; 

在您的例子,它甚至更糟。您typedef編的東西,是一種新型的編譯器理解它,使用它,你不能使用struct。背後typedef ING整個想法是,你定義了一個新的類型,所以假設下面

typedef struct Node node; 

然後申報node類型的指針(注,再次node是一種),

node *anode; 

但你試圖像

struct node *anode; 

,它是錯誤的,因爲沒有爲n在上面的代碼中,struct node,它是struct Node

代碼中的另一個錯誤是,當編譯器發現

struct node_t *next; 

,因爲如果其類型是可能這樣

的結構之前,定義這已經是錯 node_t類型不存在
typedef struct Node node_t 

它會仍然是錯誤的,在node_t類型使用struct,因爲編譯器node_t不是struct這是一個新的TY pe,這又是struct Node的簡稱。

在我的經驗Typedefing結構比反正受益更多的麻煩。它不是這麼難鍵入struct Something,而不是僅僅Something。它還具有更加明確的利益,所以如果另一程序員閱讀你的代碼,他們會立即知道Something是一個struct

:因爲它被認爲是不好的做法與_t的後綴你自己定義的類型我特意更名爲node。這不一定是壞事,但多年來,我一直在與此工作,我開發了一些習慣,其中一個習慣是不使用_t作爲我自己定義類型的後綴。順便說一句,只有在我的代碼中存在,如果他們會提高可讀性很多。否則,我只需使用struct關鍵字的結構名稱即可。

+0

但是爲什麼它能以單向而不是另一種方式工作? – ead

+0

@ead你的意思是?如果你想到你做到這一點,那根本沒有意義。你在兩個不同的地方爲結構使用了不同的標籤,它沒有任何意義。一致性是非常重要的,即使你的代碼是合理的,並且能夠正確編譯,它對自身也是不適應的,所以這是不好的做法。您應該深入閱讀語法以瞭解什麼是有效的和什麼是無效的語法。我在[tag:c]中進行了5年左右的編程,但我仍然不知道所有的語法。我知道我並不是因爲經常找到以前我不知道的東西。 –

1

您正在使用不存在的類型node_t。該類型不存在,因爲類型struct Node甚至不完整,您正在使用它的別名。在結構中使用typedefs時要記住的另一件事情,不要使用struct關鍵字和別名 例如。

/* This is correct */ 
typedef struct Node 
{ 
    int x; 
    struct Node *next; 
} node_t; 

/* while these are incorrect */ 

/* Prefixing struct keyword to a typedef'ed type */ 
struct node_t *listhead; 

/* The type is inclomplete and you are using an alias of the type 
    which doesn't even exist */ 
typedef struct Node 
{ 
    int x; 
    node_t *next; 
}; 
1

您正試圖創建一個指向您尚未創建的結構的指針。所以,它應該是,

typedef struct Node{ 
int value; 
struct Node* next; 
}node_t;