结构的指针更改

Pointer of struct changes

本文关键字:指针 结构      更新时间:2023-10-16
#include<stack>
#include<iostream>
class Tree{
    private:
        struct tree{
            int val;
            tree * lChild;
            tree * rChild;
            tree * Parent;
        };
        tree *root;
    public:
        Tree();
        void insert(int x);
};
Tree::Tree(){
    root = NULL;
    std::cout<<"ROOT inside constructor : "<<root<<std::endl;
}
void Tree::insert(int x){
    tree *wst;
    wst->val = x;
    wst->lChild = NULL;
    wst->rChild = NULL;
    tree *temp = root;
    tree *p = NULL;

    std::cout<<"ROOT inside insert : "<<root<<std::endl;
    while(temp != NULL){
        p = temp;
        if(x < temp->val)
            temp = temp->lChild;
        else
            temp = temp->rChild;
    }
    std::cout<<x<<std::endl;
    wst->Parent = p;
    if(p == NULL){
        root = wst;
    }
    else{
        if(x < p->val)
            p->lChild = wst;
        else
            p->rChild = wst;
    }
}

int main(){
    Tree tree;
    tree.insert(404);
}

我想检查指针根是否等于null,但似乎不太有效。当我在方法插入中时,指针似乎从0变为0x4。如何检查结构指针是否相等的空?

在插入方法中编辑如果树没有任何节点,则不应在循环时首先输入,因为root应该是等效的null。我的问题是,它无论如何都进入此循环并在检查临时儿童时崩溃(仍未定义)。

wst指向什么?

tree *wst;
wst->val = x;
wst->lChild = NULL;
wst->rChild = NULL;
// [...]
wst->Parent = p;

哇!您的程序具有不确定的行为。难怪它崩溃了。:)

您可能需要tree* wst = new tree();。不要忘记在Tree破坏者中使用delete您的节点!

我建议不要使用Tree型加上tree型;也许致电后一个Node