gpt4 book ai didi

c++ - 在 C++ 中以双指针作为默认参数递归调用函数时出现运行时错误

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

我正在尝试做的事情:

我正在尝试删除二叉搜索树中的一个节点。但是在删除节点之前,我们首先必须搜索该节点是否存在,并且我正在检查我的搜索函数,该函数返回找到匹配项的节点的地址。

问题是什么:

执行后,程序抛出异常:Process returned -1073741819 (0xC0000005) 我相信问题出在语句(*parent) = root;但是我不知道为什么会这样。以及如何修复它。

我的代码:

结构定义为:

struct tree{
int data;
struct tree *left, *right;
};

搜索功能:

tree * search(tree *root, int value, tree **parent = NULL){

tree * target = NULL;
if (!root) return root;
if (root->data == value) return root;
if (value < root->data){
// This returns the matched node
target = search(root->left, value);
// and this stores the parent of the matched node
if (root->left->data == value)
(*parent) = root;
} else {
target = search(root->right, value);
if (root->right->data == value)
(*parent) = root;
}
return target;
}

删除函数:

void del(tree *root, int value){
tree * parent = NULL;
if (!root) return;
tree *target = search(root, value, &parent);
// Deletion logic goes here
}

最佳答案

原因很简单,*parent=... 是一个赋值。这要求 parent 是一个有效的(非空)指针。但是您使用 nullptr 作为 parent 的默认值。

您需要修复此函数的设计。这不是唯一的缺陷。

关于c++ - 在 C++ 中以双指针作为默认参数递归调用函数时出现运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51286904/

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