Edit where a pointer points within a function

2020-02-26 11:28发布

问题:

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?

回答1:

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.



回答2:

Pass it by reference:

void foo(node*& headptr)
{
     // change it
     headptr = new node("bla");
     // beware of memory leaks :)
}


回答3:

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

// f1 :
node *d = head;

f2(&d);

// f2:
void f2(node **victim) {
    //assign to "*victim"
}