我正在尝试构建一个简单的链表,使用指向下一个插入位置的指针,并逐个添加节点。
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 hello。令我困惑的部分是,在一个循环之后,insertP 应该指向新插入的节点,该节点具有 hello 一词,但即使在内部,它也没有打印出任何内容它打印出 hello 的循环,知道为什么吗?非常感谢
最佳答案
让我们把问题最小化:
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
。
关于c++ - 尖头物体失去了它的领域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10823682/