[英]AVL TREE Malloc Functionwhen inserting a new node
我最近在C中成功创建了一个bst。然后尝试创建一个AVL。这样做的第一步是在每个节点中添加一个额外的组件bf(balance factor)。
struct tnode{
int info;
struct tnode*left;
struct tnode*right;
int bf;//new field for avl tree..
};
每次malloc在插入时为新节点分配一个地址...我将其信息部分分配给用户输入的值..将左右指针设置为NULL。此外,它还将newnode的bf分配为0。在插入第一个节点(即根节点)后,程序下一次在malloc部分失败,甚至没有为newnode分配内存...我一卸下那说newnode-> bf = 0的部分,问题就消失了。为什么会这样呢?下面是我的主要函数和add()函数,它将整数作为输入并将其插入到全局声明为“ root”的根节点的树中。
int main(){
int choice,val;
deci:
printf("\n1.Insert");
printf("\n2.Display");
printf("\n3.Search.");
printf("\n4.Delete");
printf("\n5.Naa..");
scanf("%d",&choice);
switch(choice){
case 1:printf("\nEnter element to add:");
scanf("%d",&val);
add(val);
//display();
break;
case 2:display();
break;
case 3:printf("\nEnter element to search for:");
scanf("%d",&val);
search(val);
break;
case 4:printf("\nEnter element to Delete: ");
scanf("%d",&val);
deletei(val);
display();
break;
case 5:return 0;
}
goto deci;
return 0;
}
void add(int val){
struct tnode * newnode=(struct tnode * )malloc(sizeof(struct tnode *));
newnode->info=val;
newnode->left=newnode->right=NULL;
newnode->bf=0;//problem making,problem solved removing this statement
if(root==NULL){
root=newnode;
}
else{
struct tnode*tree=root;
struct tnode*ptree=NULL;
while(tree!=NULL){
if(val<tree->info){
ptree=tree;
tree=tree->left;
}
else{
ptree=tree;
tree=tree->right;
}
}
if(val<ptree->info){
ptree->left=newnode;
tree=ptree->left;
}
else{
ptree->right=newnode;
tree=ptree->right;
}
}
}
您的第一个主要错误是您仅在add()
为newnode的地址分配了空间。 您应该将其转换为:
struct tnode * newnode=(struct tnode * )malloc(sizeof(struct tnode));
在这种情况下,您将为所需节点分配整个空间。
PS。 也请退出“ goto”说明,因为使用它是一种不好的做法。
您的问题在这一行:
struct tnode * newnode = (struct tnode *) malloc(sizeof(struct tnode *))
从C参考的malloc
分配未初始化存储的大小字节
如果分配成功,则返回指向分配的内存块中最低(第一个)字节的指针
因此, malloc
分配一个内存块,并返回一个指向该块开头的指针。 malloc
的参数是要分配的内存块的大小。
在您的情况下,您正在传递sizeof(struct tnode *)
。 因此,您正在为指向struct tnode
类型的值的指针分配足够的内存。 如果要为struct tnode
本身分配内存,请将sizeof
更改为sizeof(struct tnode)
。 然后固定线应该像
struct tnode * newnode = (struct tnode *) malloc(sizeof(struct tnode))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.