[英]Insertion error or pointer error in Binary Tree
当我尝试将数字添加到二叉树中时,出现了著名的Segmentation Fault 。
我猜错误是函数inserir_no
的指针。 也许我应该使用辅助指针。
#include <stdio.h>
#include <stdlib.h>
/* create a node */
struct no {
int info;
struct no *esq;
struct no *dir;
};
/* function prototypes */
void inserir_no(struct no *arv, int x);
void inserir_no(struct no *arv, int x)
{
if(arv == NULL) {
printf("foi");
arv = (struct no *) calloc(1, sizeof(struct no));
arv->info = x;
arv->esq = NULL;
arv->dir = NULL;
}
else if(x < arv->info) {
inserir_no(arv->esq, x);
}
else {
inserir_no(arv->dir, x);
}
}
int main(void)
{
struct no *a;
int valor;
a = NULL;
/* fazer um menu depois */
scanf("%d", &valor);
inserir_no(a, valor);
printf("\nDADOS:\n%d", a->info);
return 0;
}
问题是您在插入函数中对arv
所做的更改
if(arv == NULL) {
printf("foi");
arv = (struct no *) calloc(1, sizeof(struct no));
arv->info = x;
arv->esq = NULL;
arv->dir = NULL;
}
不要在调用方中更改传入的指针。 什么函数接收存储在调用者的变量地址的拷贝,所以当你只是拷贝覆盖calloc
内存。
要使函数更改调用方中的变量,请使其带有指向指针的指针,
void inserir_no(struct no **arv, int x);
并传递指针的地址。
inserir_no(&a, valor);
在main
else if(x < arv->info) {
inserir_no(&(*arv)->esq, x);
}
else {
inserir_no(&(*arv)->dir, x);
}
在递归调用中,以及
if(*arv == NULL) {
printf("foi");
*arv = (struct no *) calloc(1, sizeof(struct no));
(*arv)->info = x;
(*arv)->esq = NULL;
(*arv)->dir = NULL;
}
检查的值a
最后的前右侧printf()
中main()
它仍然是NULL
。 你需要的引用传递a
为内存分配你中要使用能够回调函数main()
在inserir_no()
函数中,您需要更新以获取指向struct no
指针的指针:
void inserir_no(struct no **arv, int x)
在函数本身中,您需要将对arv
每个引用更新为一个引用:
if(*arv == NULL) {
printf("foi");
*arv = (struct no *) calloc(1, sizeof(struct no));
(*arv)->info = x;
//... and the rest, just didn't want to finish it off
然后在main()
传递结构的地址:
inserir_no(&a, valor);
还有两个注意事项:
free()
分配的内存 main()
使用了它,因此不再需要) 调用为inserir_no(&a, valor);
并将函数的签名更改为inserir_no(struct no **arv , int x)
那么它将通过传递地址而不是指针的值来工作。
*arv
将是pointer to struct no
的pointer to struct no
因此请在每个位置使用它而不是仅使用arv
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.