繁体   English   中英

二叉树中的插入错误或指针错误

[英]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);

还有两个注意事项:

  1. 您现在遇到了内存泄漏,您需要在离开前free()分配的内存
  2. 如果在使用函数之前就声明了该函数,则不需要额外的原型。 (在这种情况下,您在顶部声明了它,然后在main()使用了它,因此不再需要)

调用为inserir_no(&a, valor);

并将函数的签名更改为inserir_no(struct no **arv , int x)

那么它将通过传递地址而不是指针的值来工作。

*arv将是pointer to struct nopointer to struct no因此请在每个位置使用它而不是仅使用arv

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM