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 point
Pass it by reference:
void foo(node*& headptr)
{
// change it
headptr = new node("bla");
// beware of memory leaks :)
}
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.
Pass a node ** as an argument to your function:
// f1 :
node *d = head;
f2(&d);
// f2:
void f2(node **victim) {
//assign to "*victim"
}