我创建了两个结构
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);
可以看到insert函数成功的进入了第一个if并且操作了root=newnode;这一行,并且可以看到它给出的地址。
但是当这个函数结束时,我回到主函数来访问它 printf("%d",BSThead->root);
这一行只打印 0,我认为这意味着 BST->root 当前为空。
据我所知,与普通值不同,malloc 函数创建的数据具有其函数范围。所以我想虽然 newnode 是在插入函数中创建的,但当插入函数结束时不会像普通变量一样被销毁,因此我可以在程序运行时一直使用它。
最佳答案
这些行:
if(root==NULL)
{
root=newnode;
return 1;
}
修改函数中的 root
但不要更改调用函数中相同变量的值。
调用函数中 root
的值继续为 NULL,并且您泄漏了通过调用 malloc
分配的每个节点。
解决此问题的一种方法是将指针传递给 root
。
int insert(struct node** root, int value)
{
...
if(*root==NULL)
{
*root=newnode;
return 1;
}
...
}
并调用该函数使用:
insert(&(BSThead->root),10);
关于c - 使用 malloc 函数的指向数据不断消失在它之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30387449/