Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About reference to pointers

I've been making a tree, because planting a trees will save the planet (or just the program).

class Tree {
  Node* root;
  // ...
  void insert(int value){
    private_insert(value, root);
  }
  void insert_private(int value, node* n){
    if(n == nullptr){
      n = new node(value);
    } else {
      your standard recursive insertion function here
    }
  }
  // ...
};

Long story short i've tried using shared_ptrs first, but the the insert() function will never add any element into my tree. I thought i might be doing something wrong with shareds so i tried raw pointers and i got the same non-inserty resoults.

Turns out i need to pass a reference my root/nodes.

void insert_private(int value, node*& n) {...};

I understand that if i dont pass something as reference then a copy is made. But if a pointer holds an address, doesnt it's copy hold the same address? if i make a new() to a non-referenced pointer why doesnt it stick to my root/nodes?

The why is my question here, i can accept it that it works like this, my tree works, but i dont know why its like this.

edit: After reading the comments i created this small expert level program:

void fn(int* i){
  cout << "Address of local in fn before change: " << i << endl;
  i = new int(2);
// so basically here we made a new int, and i will get the address of 
// this integer and will point to there, what we passed on before 
// becomes irrelevant
  cout << "Address of local in fn after change: " << i << endl;
}
void fn2(int **i){
  cout << "Address of local in fn2 before change: " << i << endl;
  *i = new int(2);
  cout << "Address of local in fn2 after change: " << i << endl;
}
int main(){
  int* p = nullptr;
  cout << "Address of p: " << p << endl;
  fn(p);
  cout << "p& is: " << &p << endl;
  fn2(&p);

  cin.get();
  return 0;
};

Thank you, everyone, for the answers, it helped a lot. random.org will determine who's the one who will get the approved answer thing.

like image 472
val Avatar asked Jul 16 '26 07:07

val


2 Answers

Yes it's a copy and it holds the same address, but you are assigning only to the copy which is then thrown away when the function returns. The original is unaltered. That's your problem.

As an aside, IMHO, if you are altering the value of a parameter, you should use a pointer, hence a pointer to a pointer in your case. It makes it much more obvious to the reader that you're changing the value.

like image 93
Paul J. Lucas Avatar answered Jul 18 '26 21:07

Paul J. Lucas


n = new node(value); is an assignment.

The pointer gets a new value. Now it points to somewhere else. The pointer was passed by value, so the calling code won't see any change - the assignment only had a local effect.

like image 27
Karoly Horvath Avatar answered Jul 18 '26 21:07

Karoly Horvath



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!