gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:04 25 4
gpt4 key购买 nike

我创建了这个函数,它应该创建一个随机生成的二叉树,它工作正常,但在函数的末尾,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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com