Reputation: 273
I've been trying to implement a bst, in C. I think I'm almost there, but in my add node function, I create a temporary node called current to store the current node which is visited in the tree. Then when I modify the current node, my orignal pointer is not modified after the function finishes.
I've read up about this, and I think I may need a pointer of a pointer, but I stil don't quite know how to updated original struct.
Upvotes: 2
Views: 616
Reputation: 6831
You are right that the problem has to do with the pointer to a pointer in bstlist_add
. Here's an example that should help you figure out what you need to change in your code.
int a=10;
int b=20;
void noChange(int * pSomeInt);
void change(int ** ppSomeInt);
int main(int argc,char * argv[])
{
int * pMainInt=&a;
noChange(pMainInt);
//pMainInt will still point to a
//since the parameter to change is int **, we have to use & here
change(&pMainInt);
//pMainInt now points to b
return 0;
}
void noChange(int * pSomeInt)
{
//while pSomeInt is a pointer, it is a copy of pMainInt, not a pointer to it
//so this creates a pointer to the parameter, pSomeInt, itself
int ** ppSomeInt=&pSomeInt;
//so this changes the parameter, pSomeInt
*ppSomeInt=&b;
}
void change(int ** ppSomeInt)
{
//ppSomeInt is a pointer to pMainInt, which is itself an int *
//so *ppSomeInt is pMainInt and not a copy of it
*ppSomeInt=&b;
}
Upvotes: 1