c++ - 尖头物体失去了它的领域

标签 c++

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

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/

相关文章:

C++ union 位域任务

c# - 计算功能限制的最佳方法是什么?

c++ - 返回的通用 lambda 的参数据称会影响自由函数的参数

c++ - 虚拟继承、默认构造函数和额外复制

c++ - C++中的对象实例化

C++ 错误 : Invalid conversion from 'char' to 'const char*'

iPhone-Cocos2d-Box2d游戏#include <list>问题

python - [咖啡] : Check failed: ShapeEquals(proto) shape mismatch (reshape not set)

c++ - OpenCV Hog 检测器 - 调试断言错误

c++ - 链接到 Xcode 中的库 - 静态或动态