我必须通过在每个节点中插入有关药物的数据来创建二叉搜索树。节点按字符NAME排序。我发现错误,strcmp(name,(*parent)->name) < 0
出现分段错误错误。这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct date
{
int dd,mm,yyyy;
};
typedef struct node
{
char name[50];
float price;
int amount;
struct date date_rel;
struct date date_exp;
struct node *left , *right;
} node;
node *insert_node(node **parent,char name[])
{
node *current = NULL;
if(*parent == NULL)
{
current = (node *) malloc(sizeof(node));
strcpy(current->name,name);
printf("\nPrice =");
scanf("%f",¤t->price);
printf("\nAmount =");
scanf("%d",¤t->amount);
printf("\nRelease date =");
scanf("%d.%d.%d",¤t->date_rel.dd,¤t->date_rel.mm,¤t->date_rel.yyyy);
printf("\nExpiration date =");
scanf("%d.%d.%d",¤t->date_exp.dd,¤t->date_exp.mm,¤t->date_exp.yyyy);
*parent = current;
}
else
{
if(strcmp(name,(*parent)->name) < 0)
{
(*parent)->left = insert_node(&(*parent)->left,name);
}
else
{
(*parent)->right = insert_node(&(*parent)->right,name);
}
}
return *parent;
}
int main()
{
node *root = NULL;
char name[50] ;
int total_prod;
printf("The total number of medicines is:");
scanf("%d",&total_prod);
while(total_prod != 0)
{
printf("Name =");
scanf("%s",name);
insert_node(&root,name);
total_prod--;
}
return 0;
}
答案 0 :(得分:2)
很有可能是因为left
为right
时您未初始化*parent
和NULL
指针。由于它们未初始化,它们将具有不确定值,并且实际上它将看似随机,并且很可能不等于NULL
,这导致您将它们用作有效指针并且您将未定义的行为并获得崩溃。
在*parent = current
分配之前,您需要将left
和right
的{{1}}和current
指针初始化为NULL
。