gpt4 book ai didi

c - 插入新节点时的AVL TREE Malloc Function

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

我最近在 C 中成功创建了一个 bst ..然后我的尝试是创建一个 AVL ..这样做的第一步是添加一个额外的每个节点中的组件 bf(平衡因子)..我按如下方式进行。

    struct tnode{
int info;
struct tnode*left;
struct tnode*right;
int bf;//new field for avl tree..
};

每次 malloc 在插入时为新节点分配一个地址...我将其信息部分分配给用户输入的值..将左右指针设置为NULL。除此之外,它还分配了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;

}
}


}

最佳答案

您的问题出在这一行:

struct tnode * newnode = (struct tnode *) malloc(sizeof(struct tnode *))

来自C reference对于 malloc

Allocates size bytes of uninitialized storage

If allocation succeeds, returns a pointer to the lowest (first) byte in the allocated memory block

所以malloc分配一个内存块并返回一个指向这个 block 开始的指针。malloc 的参数是您要分配的内存块的大小。

在您的情况下,您正在传递 sizeof(struct tnode *)。因此,您为指向类型 struct tnode 的值的指针分配了足够的内存。如果要为 struct tnode 本身分配内存,请将 sizeof 更改为 sizeof(struct tnode)。那么固定线应该是这样的

struct tnode * newnode = (struct tnode *) malloc(sizeof(struct tnode))

关于c - 插入新节点时的AVL TREE Malloc Function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51095245/

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