【发布时间】:2015-03-14 09:09:59
【问题描述】:
我创建了这个函数,它应该创建一个随机生成的二叉树,它工作正常,但是在函数的末尾 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;
}
【问题讨论】:
-
C是传值,你需要一个指向
creaAlbero中的指针参数的指针来修改main中的root对象。 -
代码需要检查调用 malloc 的返回值以确保操作成功
-
如果 "if ((int)(rand()%n)==0)" 的结果从不为 0,则函数:'creaAlbero' 可以永远递归
-
@user3629249 在我有限制之前这是真的,但我注意到“n”超过 5 是非常罕见的,所以我把它拿掉了
标签: c function pointers malloc binary-tree