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?
Can a pointer be changed within function? If you modify the pointer inside the called function, you only modify the copy of the pointer, but the original pointer remains unmodified and still points to the original variable.
You can't change the address of a pointer (or of any variable). Once you declare the variable, it's address is firmly set, once and forever. You can, however, change the value of a pointer, just as easily as you can change the value of an int: x = 10 or p = &t.
Updating the value of a variable via pointer To update the value of a variable via pointer we have to first get the address of the variable and then set the new value in that memory address. We get the address via address of & operator and then we set the value using the value at the address of * operator.
As you know, an address of an object in C++ can be stored either through a reference or through a pointer. Although it might appear that they represent similar concepts, one of the important differences is that you can reassign a pointer to point to a different address, but you cannot do this with a reference.
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 it by reference:
void foo(node*& headptr)
{
// change it
headptr = new node("bla");
// beware of memory leaks :)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With