2

当我尝试将一个数字添加到我的二叉树中时,会出现著名的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;
}
4

3 回答 3

4

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;
}
于 2012-11-26T16:26:04.830 回答
0

Check the value of a right before the last printf() in main(), it's still NULL. You need to pass a reference of a to the function for the memory you allocated to be use able back in main()

In the function inserir_no(), you need to update to take a pointer to a pointer to a struct no:

void inserir_no(struct no **arv, int x)

In the function itself you need to update each reference to arv for a single deference:

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

Then In main() you pass the address of your struct:

inserir_no(&a, valor);

Two other notes for you:

  1. You have a memory leak right now, you need to free() your allocated memory before you leave
  2. You don't need the extra prototype if the function is declared before it's used. (in this case you declared it at the top, then used it below in main() so that's unneeded)
于 2012-11-26T16:27:38.523 回答
0

call as inserir_no(&a, valor);

and change the signature of function to inserir_no(struct no **arv , int x)

then it will work because of passing address rather than value of pointer.

*arv will be the pointer to struct noso use that at every place instead of only arv

于 2012-11-26T16:31:04.480 回答