-2

我正在尝试实现一个链接列表来保存历史信息。

我的节点结构的定义如下:

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

我不确定为什么会发生这种情况,有什么帮助吗?

谢谢, - 亚历克斯

4

2 回答 2

1

如果History声明为全局变量,则编译成功,如http://cfiddle.net/LwucyB所示。关于该问题的另一项说明与分配有关NewNode,应如下所示

NewNode = malloc(sizeof(struct HistoryNode));

您需要为结构分配空间,而不仅仅是指针。

于 2013-04-08T23:56:01.060 回答
0

您想要 malloc sizeof(HistoryNode),而不是 NewNode(它是指向 HistoryNode 的指针)。

于 2013-04-08T23:44:24.000 回答