BST插入无法正常工作 [英] BST insert not working
问题描述
我正在尝试为二进制搜索树实现代码.问题是以下代码无法正常工作,但是如果我通过双指针来插入诸如insert(struct bst ** node,data)之类的funcion,它就可以工作.我认为它也应该与传递单个指针一起使用.谁能解释这里的错误是什么?
I was trying to implement a code for binary search trees. Problem is following code is not working but it works if I pass double pointer to insert funcion like insert(struct bst** node, data). I think it should also work with passing single pointers. Can anyone explain what is the error here ?
void insert(struct bst* node, int data )
{
if (node == NULL)
{
printf("here with %d\n",data);
node = (struct bst*)malloc(sizeof(struct bst));
node->data = data;
node->left = NULL;
node->right = NULL;
}
if(data < node->data)
{
insert(node->left,data);
}
else if(data > node->data)
{
insert(node->right,data);
}
}
推荐答案
如果要更改传递给函数的指针的值,则应将其作为指针传递给指针.
If you want to change the value of the pointer passed to a function, you should pass it as pointer to a pointer.
void alloc_int(int** p)
{
*p = malloc(sizeof(int));
}
int main()
{
int* p = NULL;
alloc_int(&p);
*p = 10; // here memory for p is allocated so you can use it
free(p);
return 0;
}
与您的示例相同.您必须传递指针的地址来更改其值(指针的值是实际数据的地址).
The same thing in your example. You have to pass an address of pointer to change its value (value of the pointer is address of actual data).
这篇关于BST插入无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!