Change where the pointer points inside the function

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

node *d=head; 

I want to pass this pointer to a function by reference and edit where it points. I can pass it, but it does not change where the original pointer points, but only the local pointer in the function. Should function arguments be valid pointers? And after changing it to show another object of the same structure?

+4
source share
3 answers

You have two main options: Skip the pointer or follow the link. To follow the pointer, a pointer to a pointer is required:

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

When following the link, & used:

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

If you pass the pointer as soon as node *d , then changing d inside the function will only change the local copy, as you noticed.

+9
source

Pass it on the link:

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

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

 // f1 : node *d = head; f2(&d); // f2: void f2(node **victim) { //assign to "*victim" } 
+1
source

Source: https://habr.com/ru/post/1387958/


All Articles