L.dev
L.dev

Reputation: 93

How to modify pointer reference to struct member variable

I want to create BST in C++. When I try to assign pointer to new node - it does not change. After fucntion call it still have random value. Is it possible to do it my way?

struct wezel {
  int value;
  wezel *l_val;
  wezel *r_val;

  wezel(int aValue) {
    value = aValue;
    l_val = NULL;
    r_val = NULL;
  }
};

struct tree {
   wezel *root;

   tree(wezel *aNode) {
     root = aNode;
   }
};

void addNode(int aValue, wezel aNode) {
   if(aValue < aNode.value) {
      if(aNode.l_val == NULL) {
            wezel pt = wezel(aValue);
            wezel *point = &pt;
        aNode.l_val = point; //do not work
      } else {
        return addNode(aValue, *aNode.l_val);
      }
   } else if(aValue > aNode.value) {
      if(aNode.r_val == NULL) {
            wezel pt = wezel(aValue);
            wezel *point = &pt;
        aNode.r_val = point; //do not work
      } else {
        return addNode(aValue, *aNode.r_val);
      }
   }

};

Upvotes: 0

Views: 76

Answers (1)

Hack06
Hack06

Reputation: 1092

wezel pt = wezel(aValue);
wezel *point = &pt;
aNode.l_val = point;

Here you are creating a pt object of type wezel, which will get destroyed once it goes out of the scope, while the pointers 'point' and aNode.l_val still pointing to its address. (By the way 'point' will also get destroyed upon leaving the scope.)

Instead, you are supposed to create a new object, linked to aNode.l_val like this:

aNode.l_val = new wezel(aValue);

And don't forget to properly dispose your nodes with the respective 'delete' statements.

Upvotes: 1

Related Questions