Reputation: 2491
When you have a function like this, the formal parameter is a reference, it becomes another name for the actual argument, so that when we modify the formal parameter inside the function, the original variable outside the function is changed.
void add_five(int& a)
{
a += 5;
}
int main()
{
int number = 3;
add_five(number);
std::cout << number << std::endl; // prints 8
return 0;
}
I have some code which works on a linked lists. And I am passing two Node*
s into the function.
void LinkedList::move_five_nodes(Node* ptr1, Node* ptr2) { ... }
...
void LinkedList::anotherFunction()
{
Node* leader;
Node* trailer;
...
move_five_nodes(leader, trailer);
...
}
I think that the rvalues memory addreses inside the leader
and trailer
pointer variables will be assigned into the Node*
lvalues ptr1
and ptr2
.
Node* ptr1 = leader;
Node* ptr2 = trailer;
The issue is that ptr1
and ptr2
are independent local variables inside the function. Initially, they point to the same place as the actual argument pointers. However, my function moves some nodes, and at the end of the function, the values of ptr1
and ptr2
are changed. I want these changes to also be in the original variables leader
and trailer
, just like references. So even when ptr1
and ptr2
expire, leader
and trailer
should go into their positions.
How would I do this? Maybe type cast the pointers into int&
? Or maybe use pointers to pointers? I want to pass a pointer by reference, but I'm not sure how to do that.
Upvotes: 4
Views: 4802
Reputation: 37
#include <iostream>
void test(int& ref);
int main()
{
int* pointer = new int(10);
std::cout << "before" << *pointer << std::endl ;
test(*pointer);
std::cout << "after" << *pointer << std::endl;
delete pointer;
}
void test(int& ref)
{
ref = 20;
}
Upvotes: 0
Reputation:
I want to pass a pointer by reference, but I'm not sure how to do that.
For this, consider the following snippet
#include <iostream>
void test(int*& t)
{
t = nullptr;
}
int main()
{
int* i = new int(4);
test(i);
if (i == nullptr)
std::cout << "I was passed by reference" << std::endl;
}
in which is is passed by reference to test, where it is set to nullptr and the program prints: I was passed by reference
.
I think this example should make clear how to pass a pointer by reference to a function.
So in your case the function signiture must change to
void LinkedList::move_five_nodes(Node*& ptr1, Node*& ptr2) { ... }
Upvotes: 6