When I try to add a number into my binary tree, appears the famous Segmentation Fault.
I guess the error is the pointer in function inserir_no. Maybe I should use a pointer aux.
#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;
}
The trouble is that the changes you made to
arvin the insert functiondon’t change the passed-in pointer in the caller. What the function receives is a copy of the address stored in the variable in the caller, so only the copy is overwritten when you
callocmemory.To make the function change the variable in the caller, make it take a pointer to a pointer,
and pass the addresses of the pointers.
in
main, andin the recursive calls, as well as