Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer Value LOSS

Tags:

c++

pointers

I have a problem root value is returning to NULL everytime I go out from the insert function I cant really understand why the pointer doesn't keep it's value.

int main(int argc, char *argv[])
{
    int input;
    node* root = NULL;
    while (input >0 ) {
          cout<< "Enter a Number:";
          cin>> input;
          insert (root,input);
    }
    printall(root);
    system("PAUSE");
    return 0;
}

void insert(node* _node,int val)
{

    //#if 0
    cout << "In insert before" << _node;
    if (_node == NULL) {
            _node = new node;
            _node->val = val;
            _node->left = NULL;
            _node->right = NULL;
            return;
    }
    //#endif
    if(_node->val > val) {
        insert(_node->left,val);
    } else if (_node->val < val) {
        insert(_node->right,val);
    }
    return;        
}
like image 443
sicko86 Avatar asked Sep 15 '26 06:09

sicko86


2 Answers

The pointer isn't "losing" it's value. You need to pass a pointer to pointer to node to insert -- then it can "return" a pointer to node through the parameter.

like image 70
Alex D Avatar answered Sep 16 '26 18:09

Alex D


You are passing root by value so it cannot be modified by the callee, you have to pass it by reference

void insert(node** _node,int val);
insert (&root,input);
like image 45
Musa Avatar answered Sep 16 '26 20:09

Musa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!