我正在尝试实现一个链表来保存历史信息。
节点结构的定义如下:
struct HistoryNode {
int Value;
struct HistoryNode *Last, *Next;
};
我还创建了另一个结构来包含指向列表中头/尾/当前节点的指针:
struct _History {
struct HistoryNode *Head, *Tail, *Current;
} History = {
NULL, NULL, NULL,
};
最后,我创建了一个函数来将一个节点添加到列表中:
void AddHistory(void) {
struct HistoryNode *NewNode;
//Allocate new node memory
NewNode = malloc(sizeof(NewNode));
if(NewNode == NULL) {
Die("malloc(%d) failed", sizeof(NewNode));
}
//Re-arrange pointers in new node and head/tail/current
if(History.Current == NULL) {
NewNode->Next = NULL;
NewNode->Last = NULL;
History.Current = NewNode;
History.Head = NewNode;
History.Tail = NewNode;
} else {
NewNode->Next = NULL;
NewNode->Last = History.Current;
History.Current = NewNode;
History.Tail = NewNode;
}
}
GCC将此错误连同几个错误一起返回:
Scribe.c: In function 'AddHistory':
Scribe.c:509:15: error: request for member 'Current' in something not a structure or union
Scribe.c:513:16: error: request for member 'Current' in something not a structure or union
Scribe.c:514:16: error: request for member 'Head' in something not a structure or union
Scribe.c:515:16: error: request for member 'Tail' in something not a structure or union
Scribe.c:518:32: error: request for member 'Current' in something not a structure or union
Scribe.c:520:16: error: request for member 'Current' in something not a structure or union
Scribe.c:521:16: error: request for member 'Tail' in something not a structure or union
我不知道为什么会发生这种情况,有什么帮助吗?
谢谢,——亚历克斯
如果将History
声明为全局变量,则编译成功,如http://cfiddle.net/LwucyB所示。关于该问题的另一个注意事项与NewNode
的分配有关,应如下所示
NewNode = malloc(sizeof(struct HistoryNode));
你需要为结构体分配空间,而不仅仅是指针。
您需要malloc sizeof(HistoryNode),而不是NewNode(它是一个指向HistoryNode的指针)