指向的对象失去了它的字段

pointed object lost its field

本文关键字:字段 对象 失去      更新时间:2023-10-16

我正在尝试构建一个简单的链表,使用指向下一个插入位置的指针,并逐个添加一个节点。

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