# Question about adding to a BST with * and **

This is a discussion on Question about adding to a BST with * and ** within the C Programming forums, part of the General Programming Boards category; Hello, So, I wrote a code last week using pointer to a pointer to add a node to a BST ...

1. ## Question about adding to a BST with * and **

Hello,

So, I wrote a code last week using pointer to a pointer to add a node to a BST

Code:
```orest addTree(Forest *root, int val)
{
if (*root== NULL)
{
//if the root node is null (tree is empty)
//this means if this is your first node
//or if you've made your way down the tree
//and this is where you need to insert the node
*root=malloc(sizeof(Tree));
(*root)->value=val;
(*root)->left=NULL;
(*root)->right=NULL;
}
else if (val < (*root)->value)
{
//if the value you want to insert is less than the
//value in the node, then recursive call this function, going left
}
else if (val >= (*root)->value)
{
//if the value you want to insert is greater or = than the
//value in the node, then recursive call this function, going right
}```
But now as I try to do this with just using single pointers
Code:
```Forest buildBST(Forest root, int val)
{
if(root==NULL)
{
root=malloc(sizeof(Tree));
root->value=val;
root->left=NULL;
root->right=NULL;

}
else if (val <= root->value)
{
buildBST(root->left, val);
}
else if (val > root->value)
{
buildBST(root->right, val);
}
return root;```
But it doesn't seem to work.

Is there something different that needs to be done when implementing BST's given a pointer to a pointer rather than juts a pointer?

Thanks!

2. Yes. C only does pass by value. Therefore, if you want to change the value of something in a function, and have that change persist after the function, then you need to pass a pointer to that thing. If you want to change an int, you pass a pointer to an int, and change the int through the pointer. Same thing applies if that thing is already a pointer: you pass a pointer to a pointer. If Forest is a pointer to something, and you wish to change what it points to, i.e. you want it to hold the value of malloc after the function is done, you have to pass it as Forest *root, and use *root = malloc in the function.

3. Awesome - you're attempting a BST without this

Popular pages Recent additions