c - 带有指针的 C 错误中的 Malloc 函数

标签 c function pointers malloc binary-tree

我创建了这个函数,它应该创建一个随机生成的二叉树,它工作正常,但在函数的末尾,root == NULL,我不明白为什么!

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>

#define MAX_B 7

typedef struct _ramo{
    int nbanane;
    struct _ramo *dx;
    struct _ramo *sx;
}ramo;

void creaAlbero(ramo *root, int n){
    printf("%d\n",n);
    root = malloc(sizeof(ramo));
    root->nbanane=rand()%MAX_B;
    printf("BANANA! %d\n",root->nbanane);
    root->dx=NULL;
    root->sx=NULL;
    if ((int)(rand()%n)==0)
        creaAlbero(root->dx, n+1);
    if ((int)(rand()%n)==0)
        creaAlbero(root->sx, n+1);
 }

int main(){
    srand((unsigned int)time(NULL));
    ramo *root=NULL;
    creaAlbero(root, 1);
    if (root==NULL) {
        printf("EMPTY!!");
    }
    return 0;
}

最佳答案

您将 root 设置为 NULL:

ramo *root=NULL;

然后将其副本传递给 creaAlbero():

creaAlbero(root, 1);

修改副本

root = malloc(sizeof(ramo));

然后返回。原来的 root 仍然是 NULL,因为它没有任何改变。

考虑从 creaAlbero() 返回 root:

ramo * creaAlbero(int n){
  printf("%d\n",n);

  ramo *root = malloc(sizeof(ramo));
  root->nbanane=rand()%MAX_B;
  printf("BANANA! %d\n",root->nbanane);
  root->dx=NULL;
  root->sx=NULL;

  if ((int)(rand()%n)==0)
    root->dx = creaAlbero(n+1);
  if ((int)(rand()%n)==0)
    root->sx = creaAlbero(n+1);

  return root;
}

int main(){
  srand((unsigned int)time(NULL));
  ramo *root=NULL;
  root = creaAlbero(1);
  if (root==NULL) {
    printf("EMPTY!!");
  }
  return 0;
}

示例:https://ideone.com/dXiv8A

关于c - 带有指针的 C 错误中的 Malloc 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27972508/

相关文章:

c - 读取原始音频文件

C if else 条件

c - 为什么我会遇到以下程序的段错误?

c - 函数指针的自由数组

c - 我们如何打印部分填充的整数数组?如果是整数,我们不能使用 '\0'

c - 暴力破解代码未运行

javascript - includes() 不适用于所有浏览器

javascript - 注入(inject)的 JavaScript 函数未执行

c++ - 实现 [B,C]=f(A) 语法(函数 f 作用于具有两个或多个输出数组的数组)

pointers - 将接口(interface)实体放入 Google Cloud Datastore 失败