指针后面的值通过打印来改变。

问题描述 投票:0回答:2

我想用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++ pointers binary-tree
2个回答
3
投票

你正在给非静态局部变量分配指针,非静态局部变量在从函数返回时将无效,你应该用dinamically allocate节点来代替。

换句话说,你应该使用

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

而不是

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

也做这样的 node -> leftNode.

© www.soinside.com 2019 - 2024. All rights reserved.