[英]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.