简体   繁体   中英

C Implementing a Binary Search Tree

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM