gpt4 book ai didi

C++ 段错误(核心已转储)

转载 作者:行者123 更新时间:2023-11-28 03:04:42 33 4
gpt4 key购买 nike

所以我遇到的问题是段错误。我正在尝试实现一个 AVLtree,我相信我的这部分代码是问题所在,但我无法确定我做错了什么。

我的 AVLtree 类的一部分:

  Node* AVLtree::findNode(string cityID){
Node *thisNode = this->rootNode;
while(thisNode!=0){
if(thisNode->getCity()->getName().compare(cityID)==0){return thisNode;
}else if(thisNode->getChildR()->getCity()->getName() < cityID){ thisNode = thisNode->getChildR();
}else{thisNode = thisNode->getChildL();}
}
return this->rootNode;
}

我的主文件:

     int main(){
....
City city1("BoomTown", "EU", 1.01, 2.02);
....
AVLtree avltree1(&city1);
cout<< "TEST 1: AVLtree with city paramter of city1 (" << city1.getName()<< ")" << endl;
cout << "TEST 2: Getting name of city1: " << avltree1.findNode("BoomTown")->getCity()->getName() << endl;

我的 City 类和 Node 类都可以工作,我可以创建一个 AVLtree。我似乎无法在其中找到节点。

这是我的输出:

    $ ./mainTest
TEST 1: AVLtree with city paramter of city1 (BoomTown)
Segmentation fault (core dumped)

如果这是一个简单的错误,我很抱歉,但我是 C++ 的新手,需要时间和练习来学习:)提前致谢。

(附注:如果您需要更多代码,请询问)

最佳答案

在您的代码中,您似乎检查了当前节点是否为空,但在访问它之前没有检查子节点是否为空:

while(thisNode!=0) {
// ...
if(thisNode->getChildR()->getCity()->getName() < cityID){
^^^^^^^^^^^
here

关于C++ 段错误(核心已转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20025242/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com