簡體   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