[英]problem in creating binary search tree in c language
This code creates a binary search tree but it runs sometimes normally and sometimes makes errors, even without changing anything in the code.这段代码创建了一个二叉搜索树,但它有时运行正常,有时会出错,即使没有更改代码中的任何内容。
I can't get why this happening, what's the mistake?我不明白为什么会发生这种情况,这是什么错误?
Even I changed the function that I used to create the tree from recursive to iterative but the same results.即使我将用于创建树的 function 从递归更改为迭代,但结果相同。
#include <stdio.h>
#include <stdlib.h>
typedef struct sommet{
struct sommet * fg;
int val;
struct sommet * fd;
}sommet;
typedef sommet* ptrm;
ptrm creearbre(ptrm arbre,int ele);
void impression(ptrm arbre);
ptrm creearbre_rec(ptrm arbre,int ele);
int main()
{
ptrm arbre=NULL;
int tarbre,n;
printf("entre la taille de l'arbre:");
scanf("%d",&tarbre);
for(int i=0;i<tarbre;i++)
{
printf("entre l'element %d: ",i+1);
scanf("%d",&n);
arbre=creearbre_rec(arbre,n);
}
impression(arbre);
return 0;
}
ptrm creearbre_rec(ptrm arbre,int ele)
{
if(arbre==NULL)
{
arbre=malloc(sizeof arbre);
arbre->val=ele;
arbre->fd=NULL;
arbre->fg=NULL;
}
else if(arbre->val > ele)
arbre->fg=creearbre_rec(arbre->fg,ele);
else
arbre->fd=creearbre_rec(arbre->fd,ele);
return arbre;
}
void impression(ptrm arbre){
if(arbre != NULL){
printf(" %d -->", arbre->val);
impression(arbre->fg);
impression(arbre->fd);
}
}
ptrm creearbre(ptrm arbre,int ele){
ptrm p,q=arbre,r=NULL;
p=malloc(sizeof arbre);
p->val=ele;
p->fd=NULL;
p->fg=NULL;
if(arbre==NULL){
arbre=p;
}
else{
while(q!=NULL){
r=q;
if(ele > q->val)
q=q->fd;
else
q=q->fg;
}
if(ele > r->val)
r->fd=p;
else
r->fg=p;
}
return arbre;
}
The program has undefined behavior due to using an invalid size in the allocation of memory in statements由于在语句中分配 memory 时使用了无效的大小,程序具有未定义的行为
arbre=malloc(sizeof arbre);
and和
p=malloc(sizeof arbre);
There are allocated memory for pointers instead of objects of the structure type.为指针而不是结构类型的对象分配了 memory。
You need to write你需要写
arbre=malloc(sizeof *arbre);
p=malloc(sizeof *arbre);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.