[英]What's the difference between `typedef struct X { }` and `typedef struct { } X`?
[英]Struct X in Struct X?
這可能很簡單,但是如何在C中的struct x中得到一個struct x? 例如:
typedef struct _Node {
Node node;
} Node;
我做了一些研究並嘗試使用指針,如下所示:
typedef struct _Node {
struct Node *node;
} Node;
雖然這會將變量節點作為指針(我不想要),但我只想讓它成為Node結構的一個實例。 謝謝你的幫助。 :)
編輯:
基本上我要做的是:
Node current = createNode(...);
while (true) {
Node node = createNode(..., ¤t);
addToList(node);
current = somethingElse();
}
你可以想象,我想要一個常規節點進入createNode()函數:
Node createNode(..., Node node) {}
typedef struct node {
struct node node;
} node_s;
這將導致“無限遞歸”。 換句話說,它的大小將是無限的。 編譯器無法回答這個問題: 要分配多少內存 ? 因此它會拋出一條診斷信息。
這就是為什么你必須使用指針來創建自引用類型。
typedef struct node {
struct node *node;
} node_s;
順便說一下,以下划線后跟下划線或大寫字母開頭的標識符保留給實現。
那是不可能的。 因為那是不完整的類型。 沒有struct Node
內部struct Node
內部struct Node
...等等....這使得原來的結構不完整。 因此類型定義不完整。
原因是。
struct Node{}
看到struct Node
它尚未確定。 struct Node{}
所有定義之后才確定,但這只有在知道了struct Node
的類型之后才有可能導致paradox
。 但是,如果包含struct Node *
則情況會有所不同。
struct Node *
,你知道它是一個指針類型。 無論指針的類型是什么,都需要一定量的存儲空間。 struct Node{}
的定義。 因此它是一個完整的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.