2016-11-27 694 views
-1

我目前正在學習指針和結構,而且我正在進行練習。 我的目標是編寫一個函數head_insert,它基本上創建一個新的列表元素,並將其附加到前面。在C++中創建列表

注意:我知道C++中已經有了一個數據類型列表,但這只是爲了更好地行使和理解動態結構背後的概念。

我的代碼如下:

struct list{ 
    int val; 
    list *next = NULL; 
}; 

typedef list* ptr_list; 

ptr_list head_insert(ptr_list head, const int element){ 
    ptr_list tmp_head; 
    tmp_head = new list; 
    tmp_head->val = element; 
    tmp_head->next = head; 
    return tmp_head; 
} 

int main(){ 
    ptr_list head = NULL; 
    head = head_insert(head, 1); // This is the crucial step I think, as head is not initialized yet 
    head = head_insert(head, 2); 

    return 0; 
} 

的事情是,我想要的功能head_insert也上班的時候頭是空的,即我的列表是空的。但是,在調試我的代碼時,我注意到在head_insert頭的每次調用都保持爲NULL之後,會發生head(head-> val,head-> next)內的更改。

這是爲什麼?這與tmp_head的範圍有關嗎? 我怎麼能修改我的代碼以我想要的方式工作?

如果我不套頭在開始NULL,但手動分配空間並設置它的第一要素,一切工作完全正常:

head = new list; 
head->val = 1; 

感謝您的時間和幫助! 乾杯

+3

我沒有看到問題。 '頭'似乎在變化:http://coliru.stacked-crooked.com/a/baf503d3389a8cac –

+1

代碼看起來很正常。也許你在調試器時遇到了一些問題。 – arturx64

回答

1

你的代碼看起來不錯,head在調用head_insert後肯定會改變。

然而,說(頭戴式> VAL,頭戴式>未來)頭部內

變更時

是錯誤的,你從head_insert不 「變」 頭,你創建一個新對象tmp_head,然後在head_insert返回時將其分配給head

當您使用您的調試器時,您可能會注意到head仍然在head_insert執行內NULL,這是絕對正常的。之後,當函數返回時,tmp_head被複制到head(如您所做的head = head_insert(head, 1);),然後head被從NULL更改爲非NULL

+0

感謝您的回答。這很奇怪。 Eclipse Debugger在整個時間顯示頭= 0x0。然而,你說得對,當我在head_insert的每次調用之後打印頭部時,我可以看到它的價值實際上在變化。 我解決了導致我調試代碼的原始問題。它在開始時將指針設置爲NULL。我在開始時沒有這樣做,然後程序在插入/未能在列表上工作(打印出來)後終止。 – Doc