2012-05-30 51 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乐于帮忙! –