我创建了两个结构尖锐的数据不断消失
typedef struct node
{
struct node* left;
struct node* right;
int data;
} node;
typedef struct head
{
int count;
struct node* root;
} head;
,这里是我试图使用将数据插入到一棵树的功能之外吧。
int insert(struct node* root, int value)
{
node* newnode =(node*)malloc(sizeof(node));
newnode->data=value;
newnode->left=NULL;
newnode->right=NULL;
if(root==NULL)
{
root=newnode;
return 1;
}
if(value<root->data)
{
if(root->left==NULL)
{
root->left=newnode;
return 1;
}
else
{
return insert(root->left,value);
}
}
else if(value==root->data)
{
printf("data already exist\n");
free(newnode);
return 0;
}
else
{
if(root->right==NULL)
{
root->right=newnode;
return 1;
}
else
{
return insert(root->right,value);
}
}
}
,当我操作
head* BSThead=(head*)malloc(sizeof(head));
insert(BSThead->root,10);
我可以看到,插入功能成功地进入第一和如果操作线根= newnode,和我可以看到,它已给出的地址。
但是当这个函数结束时,我回到主函数来通过 来访问它printf(“%d”,BSThead-> root);
这行只是打印0,我认为这意味着BST-> root目前为空。
据我所知,由malloc函数创建的数据具有与正常值不同的功能范围。所以我认为虽然newnode是在插入函数中创建的,但是在插入函数结束时不会像正常变量一样被销毁,因此我可以在程序运行时随时使用它。
你可能需要传递指向该函数根节点指针的指针。或者你可以从函数返回新的根节点指针。对于具有相同基本诊断的SO,存在很多问题。但是,您还会将未经检查的未初始化数据从'malloc()'传递给函数,这也可能导致很多麻烦。 –