无法访问地址0xc8的内存

时间:2018-10-08 21:01:22

标签: c++ c++11

我正在编写代码以根据ID在BST中返回节点的数据。 下面是我的节点类:

 <Tooltip text={this.state.tooltipText} />

下面是我的节点构造函数:我在addNode函数中定义了ID和数据

struct Node{
int id;
string data;
Node *left;
Node *right;
Node();
};

下面是我的BST课程:

Node :: Node(){
this->left = nullptr;
this->right = nullptr;
}

以下是我的助手功能:

class BST{
private:
Node * root = nullptr;
void setRoot(Node *);
Node* getRoot();
public:
Node *addNode(BST *, int);//helper function
Node *addNode(Node *,int);
string getEntry(BST*,int);//helper function
string getEntry(Node*,int);
}

下面是我的addNode类:

Node *BST::addNode(BST *bst, int val){
addNode(bst->getRoot(),val);
}

string BST::getEntry(BST* bst,int id){
getEntry(bst->getRoot(),id);
}

下面是我的getEntry类:

Node* BST::addNode(Node* root, int val) {
Node *newNode = new Node();
newNode->id = val;
newNode->data = "Number " + to_string(val);
if (root == nullptr) {
    if (getRoot() == nullptr){
        setRoot(newNode);
    }
    setCount(getCount()+1);
    return newNode;
}
if (root->id > val) {
    root->left = addNode(root->left, val);
} else {
    root->right = addNode(root->right, val);
}
return root;
}

下面是我从main传入的节点:

string BST::getEntry(Node *base,int id) {
if (base == nullptr){
    return "";
}
if (base->id == id){
    cout<<base->data<<endl;
    return base->data;
}
getEntry(base->left,id);
getEntry(base->right,id);
}

代码可以编译,但不返回任何内容,我尝试调试,在“ return base-> data语句”处,出现错误“无法访问地址0xc8处的内存”。是什么引起了问题,我该怎么办?

这是调试代码时收到的警告。 enter image description here

1 个答案:

答案 0 :(得分:0)

if (base->id != id){
    getEntry(base->left,id);
    getEntry(base->right,id);
}

使用排序树时,您知道需要查看的是右侧节点还是左侧节点。另外,您需要返回一些内容:

if (base->id > val){
    return getEntry(base->left,id);

}     返回getEntry(base-> right,id);

但是addNode的设计非常糟糕,您不必两次传递根!