2012-05-30 86 views
0

我想構建一個簡單的鏈表,使用指向下一個插入位置的指針,並逐個添加一個節點。尖對象丟失了它的字段

Tnode* NULL_cp = 0; 
struct Tnode{ 
string word; 
Tnode* left; 
Tnode* right; 
}; 


int main(int argc, char** argv){ 
int n = 0; 
Tnode head; 
head.word = "the head"; 
head.left = NULL_cp; 
head.right = NULL_cp; 
Tnode* insertP = &head; 
while(n<argc-1){ 
    Tnode node; 
    node.word = argv[n+1]; 
    node.left = insertP; 
    node.right = NULL_cp; 
    insertP->right = &node; 
    insertP = &node; 
    cout << "inside loop: " << insertP->word << endl; 
    n++; 
} 
cout << "outside loop: the word is " << insertP->word << endl; 
} 

輸出

inside loop: hello 
outside loop: the word is 

,如果我在類型的a.out你好。這讓我感到困惑的部分是一個循環之後,insertP應該在有新插入的節點指向字你好,但它打印出來什麼,即使在循環中它打印出來你好 ,有什麼想法爲什麼?非常感謝您

回答

2

讓我們最大限度地減少問題:

while(n<argc-1) 
{ 
    Tnode node; 
    //... 
} 

node超出範圍,所以做它std::string成員。你會有懸掛在你樹中節點的指針。它在循環內工作,因爲對象還活着。外面...不是很多。

使用動態分配:

while(n<argc-1){ 
    Tnode* node = new Tnode; 
    node->word = argv[n+1]; 
    node->left = insertP; 
    node->right = NULL_cp; 
    insertP->right = node; 
    insertP = node; 
    cout << "inside loop: " << insertP->word << endl; 
    n++; 
} 

不要在最後不忘delete

+0

工作就像一個魅力,謝謝! –

+0

@ClintHui樂於幫忙! –