Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit where a pointer points within a function

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?

like image 587
Theocharis K. Avatar asked Dec 25 '11 20:12

Theocharis K.


People also ask

Can a pointer be changed within function?

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.

Can you change where a pointer points to in C?

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.

How do I change the value of a pointed pointer?

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.

Can you reassign a pointer?

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.


2 Answers

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.

like image 187
Greg Hewgill Avatar answered Oct 12 '22 08:10

Greg Hewgill


Pass it by reference:

void foo(node*& headptr)
{
     // change it
     headptr = new node("bla");
     // beware of memory leaks :)
}
like image 33
sehe Avatar answered Oct 12 '22 10:10

sehe