当我尝试为结构分配新指针时出现堆栈溢出错误
Stack overflow error when i try to assign a new pointer to a structure
当我调用函数newNode
抛出异常并说stack overflow
时,我检查了其中节点的参数说它们无法读取。
struct node
{
int data;
struct node* left;
struct node* right;
};
//function that initialeze a new node
struct node* newNode(int data) {
struct node *node = (struct node *) malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
struct node* arrayToBST(int arr[], int start, int end) {
int mid = (start + end) / 2;
struct node *root = newNode(arr[mid]);
root->left = arrayToBST(arr, start, mid - 1);
root->right = arrayToBST(arr, start, mid + 1);
return root;
}
函数newNode
很好,真正的问题在于你的函数arrayToBST
。 您正在尝试递归构建树,但您没有给它一个停止点,例如:
struct node* arrayToBST(int arr[], int start, int end) {
if (start > end) return NULL;
int mid = (start + end) / 2;
...
因此,您的程序将无休止地调用arrayToBST
函数,直到堆栈溢出。
相关文章:
- 为什么我在空指针错误(链表)中获取成员访问权限
- std::函数指针错误:无法将 &A::a 转换为类型 std::function<>&&
- 为什么我得到 munmap_chunk():无效的指针:错误
- 成员模板函数指针错误
- 删除指针时,未分配被释放的 C++ 指针错误
- Visual Studio 中的"指向引用的指针"错误不会按发生位置的文件名显示
- C++数组指针错误无法将“int*”转换为“int**”
- C++ 通过函数指针错误调用成员函数
- 从 BST 中删除元素(指针错误)
- 随机生成的多维布尔指针错误
- 在测试中使用unique_ptr时指针错误无效
- 使用 malloc 而不是 new 会导致 free():指针错误无效
- 非标准语法;使用 '&' 创建指向成员的指针错误,将成员函数分配给向量时出错
- 抽象类和唯一指针 c++ 错误
- 返回函数指针错误而不带类型定义
- 练习中出现空指针错误
- 指针错误导致的分段错误(简单..)
- free():C++中的指针错误无效
- 使用布尔值数组"表达式必须具有指向对象类型的指针"错误C++
- 指针错误的C 数组