7

I have a pointer to a struct object in C++.

 node *d=head;

I want to pass that pointer into a function by reference and edit where it points. I can pass it but it doesn't change where the initial pointer points but only the local pointer in the function. The arguments of the function must be a pointer right? And after how do I change it to show to a different object of the same struct?

Theocharis K.
  • 1,251
  • 1
  • 15
  • 43
  • You want to pass `d` to another function but have `head` change when that other function modifies `d` (via a reference)? How did the caller pass you `head`? – Mat Dec 25 '11 at 20:49

3 Answers3

12

You have two basic choices: Pass by pointer or pass by reference. Passing by pointer requires using a pointer to a pointer:

void modify_pointer(node **p) {
    *p = new_value;
}

modify_pointer(&d);

Passing by reference uses &:

void modify_pointer(node *&p) {
    p = new_value;
}

modify_pointer(d);

If you pass the pointer as just node *d, then modifying d within the function will only modify the local copy, as you observed.

Greg Hewgill
  • 890,778
  • 177
  • 1,125
  • 1,260
3

Pass it by reference:

void foo(node*& headptr)
{
     // change it
     headptr = new node("bla");
     // beware of memory leaks :)
}
sehe
  • 350,152
  • 45
  • 431
  • 590
1

Pass a node ** as an argument to your function:

// f1 :
node *d = head;

f2(&d);

// f2:
void f2(node **victim) {
    //assign to "*victim"
}
fge
  • 114,841
  • 28
  • 237
  • 319