gpt4 book ai didi

c++ - 什么是 "Read Access Violation... was nullptr"?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:11:17 24 4
gpt4 key购买 nike

我需要一些帮助。我一直在努力让我的删除功能正常工作,但无论我做什么,它总是给我一个“was nullptr”错误。我的代码有点乱,因为我一直 panic ,疯狂地尝试想到的任何事情。如果需要,我准备重新开始。我到处寻找有关 nullptr 的信息并没有真正给出我真正理解的解释。我的理解是,当您尝试取消引用指针/节点时会出现“was nullptr”错误,但我永远找不到一种方法来处理对我来说有意义的问题。非常感谢任何帮助。我的代码是:

 `

BT::BT()
{
node* root = NULL;
}

char BT::FindReplacement(node* parent, char param)
{
if (parent == NULL) //In case someone tries to delete a node while there aren't any nodes in the Tree
{
return NULL;
}

parent = parent->right;
while (parent->left != NULL)
{
parent = parent->left;
}

return parent->data;
}

void BT::leafDriver()
{
int count = 0;
leafCount(root, count);
}

void BT::leafCount(node* start, int count)
{


if ((start->left == NULL) && (start->right == NULL))
{
count++;
}

if (start->left != NULL)
{
leafCount(start->left, count);
}

if(start->right != NULL)
{
leafCount(start->right, count);
}
cout << " There are " << count << " number of leaves in the BST" << endl;

}


void BT::deletionDriver(char param)
{
deletion(root, param);
}

void BT::deletion(node* parent, char param)
{

if (parent->data < param)
{
parent->left = parent->left->left;
deletion(parent -> left, param);
cout << "checking left node" << endl;
}

else if (parent->data > param)
{
parent->right = parent->right->right;
deletion(parent->right, param);
cout << "checking right node" << endl;
}

else if (parent->data == param)
{
//Case 1: No Children
if (parent->left == NULL && parent->right == NULL)
{
delete parent;
parent = NULL;

}


//Case 2: One Child
else if ((parent->right == NULL) && (parent->left != NULL))
{
node* temp = parent;
parent = parent->left;
delete temp;
}

else if (parent->left == NULL)
{
node* temp = parent;
parent - parent->right;
delete temp;
}

//Case 3: Two Children
else if ((parent->left != NULL) && (parent->right != NULL))
{
char tempParam;
tempParam = FindReplacement(parent, param);
parent->data = tempParam;
deletion(parent->right, tempParam);
}
}

else
cout << "Item is not found in BST" << endl;
}`

最佳答案

每当你有这样的代码时:

parent = parent->right;

您需要检查新分配给父级的值是否不为空。换句话说,您的代码应始终如下所示:

parent = parent->right;
if ( parent == nullptr ) {
// handle null case
}
else {
// handle case when there is another node
}

关于c++ - 什么是 "Read Access Violation... was nullptr"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41080879/

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