指向的对象失去了它的字段
pointed object lost its field
我正在尝试构建一个简单的链表,使用指向下一个插入位置的指针,并逐个添加一个节点。
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
。
相关文章:
- 私有字段对象与私有继承?
- 如何正确实例化静态字段 tat 是另一个类对象
- 为什么最后一个推回向量的对象的字段会转移到向量的其他对象?
- 对象引用中的字段以不同的方法返回不同的值
- 基于不同字段的对象向量的排序功能
- 动态分配对象中的字段-动态分配更好还是静态分配更好?C++
- 如何从对象/类中找到第一个字段?
- 我需要帮助以连续的方式将对象的字段正确写入文件
- 更改保留指向其字段的原始指针的对象地址
- 如何在 c++98 中通过特定字段在 QList 中查找对象?
- 如何从具有多个对象/字段的类中调用方法函数
- 如何使用 stl 容器有效地存储对象?(即根据其字段的值进行搜索)
- 在对象向量中的对象字段排序
- 函数上的关键字'const'意味着对象字段完全只读?
- 类内非静态字段初始化 + 对象池 - >降低可维护性/可读性
- 使用方法影响另一个对象的字段
- 设计具有变体字段的文本类型类,其中可以存储一个或三个对象
- 无法将字段<对象名称>声明为抽象类型
- C++:字段对象可以在不存储指针的情况下知道其"parent"吗?
- 如何指定为成员字段对象调用哪个构造函数