【问题标题】:Value behind a pointer changes by printing it指针后面的值通过打印来改变
【发布时间】:2020-08-17 04:15:38
【问题描述】:

我想在 C++ 中使用指向左孩子和右孩子的每个节点的指针来构建一个简单的二叉树。我手动设置树的根,然后向树添加一个数字,但是通过在 main() 中打印它的值,指针后面的变量的值会改变它的值。

#include <stdlib.h>
#include <iostream>
using namespace std;

struct Node
{
    int data = 0;
    Node *leftNode = NULL;
    Node *rightNode = NULL;
};

void insertNode(Node *node, int newData)
{
    cout << "Testing Node: " << node -> data << " | " << &(node -> data) << endl;
    //smaller (or equal) or bigger
    if (newData > node -> data)
    {
        if (node -> rightNode == NULL)
        {
            Node newNode;
            newNode.data = newData;
            node -> rightNode = &newNode;
        }
        else
        {
            insertNode(node->rightNode, newData);
        }
    }
    else
    {
        if (node -> leftNode == NULL)
        {
            Node newNode;
            newNode.data = newData;
            node -> leftNode = &newNode;
            cout << "Added Node: " << (node -> leftNode) -> data << " AT " << &(node -> leftNode -> data) << endl;
        }
        else
        {
            insertNode(node -> leftNode, newData);
        }
    }
}

int main()
{
    Node firstnode;
    firstnode.data = 42;
    Node *pointer = &firstnode;
    //insert nodes
    /*for (int i = 0; i < 10; i++)
    {
        cout << "Inserting new Element: " << (10 + i) << endl;
        int newI = 10 + i;
        insertNode(&firstnode, newI);
    }*/
    cout << "Inserting new Element: " << (10) << endl;
    int newI = 10;
    insertNode(&firstnode, newI);
    cout << "in main " << firstnode.leftNode -> data << " | " << &(firstnode.leftNode -> data) << endl;
    cout << "in main2 " << firstnode.leftNode -> data << " | " << &(firstnode.leftNode -> data) << endl;

    return 0;
}

输出:

Inserting new Element: 10
Testing Node: 42 | 0x61feec
Added Node: 10 AT 0x61fea8
in main 10 | 0x61fea8
in main2 6422216 | 0x61fea8

你有什么办法解决这个问题吗?

【问题讨论】:

  • 不要在现代 C++ 中使用 NULL。使用nullptr
  • 当您在insertNode 中创建newNodes 时,您会在堆栈而不是堆上创建它们。然后它们立即超出范围,并且您刚刚设置的指针现在悬空。

标签: c++ pointers binary-tree


【解决方案1】:

您正在分配指向非静态局部变量的指针。 从函数返回时,非静态局部变量将无效。 您应该改为动态分配节点。

换句话说,你应该使用

Node* newNode = new Node;
newNode -> data = newData;
node -> rightNode = newNode;

而不是

Node newNode;
newNode.data = newData;
node -> rightNode = &newNode;

node -&gt; leftNode也这样做。

【讨论】:

  • 为什么值会改变?没有调用任何函数。据我了解,在第一次打印值后,没有任何东西放在堆栈上。为什么第一个打印的值与第二个打印的不同?
  • @StackExchange123 用于cout&lt;&lt; 运算符可以实现为函数。函数调用使用堆栈。一些也使用堆栈的局部变量可能会在实现中使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多