2013-04-08 67 views
-2

我試圖實現鏈接列表來保存歷史信息。結構和鏈表(C)

我的節點結構的定義如下:

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吐出這個回來ou t以及幾個錯誤:

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 

我不知道爲什麼會發生這種情況,有什麼幫助?

謝謝, - 亞歷

回答

1

如果將History聲明爲全局變量,則編譯成功,如http://cfiddle.net/LwucyB中所示。對這個問題,還應注意有關的NewNode分配應該是如下

NewNode = malloc(sizeof(struct HistoryNode)); 

您需要分配的結構,而不是隻是空間的指針。

+0

我不確定這是否正確...「歷史」被定義爲全局類型爲_History的對象。如果我進行了更改,建議我從GCC獲得: https://gist.github.com/anonymous/5341710 – Alex 2013-04-08 23:59:40

+0

@ user1509246 ..能否請您分享完整的文件。如果'History'是一個全局變量,那麼我可以在本地構建它。請檢查這個鏈接:http://cfiddle.net/LwucyB – Ganesh 2013-04-09 00:04:15

+0

發佈完整的源文件可能不會有太大的幫助,因爲它是巨大的,你可能會迷失在它的內部。但是,您發佈的鏈接與源文件中的內容完全相同。 難道是我的編譯器不支持它嗎?我正在使用: gcc(GCC)4.7.2 版權所有(C)2012自由軟件基金會,Inc. – Alex 2013-04-09 00:14:11

0

你想對malloc的sizeof(HistoryNode),不NewNode(這是一個指向HistoryNode)。

+0

嗯,當我添加這個,我得到這個錯誤: Scribe.c:504:29:錯誤:'HistoryNode'未申報(首次在此函數中使用) – Alex 2013-04-08 23:46:00

+0

在問題中,我們可以觀察到'HistoryNode'不是一個'typedef'。因此,當我們需要分配時,我們需要指定'malloc(sizeof(struct HistoryNode));'。但是,從邏輯角度來看,分配指針在語法上很好,即使它不正確。 – Ganesh 2013-04-09 00:22:30