Reputation: 1383
So i have a reasonable understanding of pointers but i was asked what the difference between these are:
void print(int* &pointer)
void print(int* pointer)
I'm still a student myself and im not 100%. Im sorry if this is basic but my googleing skills failed me. Is there anyway you can help me understand this concept a bit better. I haven't used c++ in a long time, and i am trying to help to tutor a student, and i am trying to solidify my conceptual knowledge for her.
Upvotes: 2
Views: 106
Reputation: 258648
The first passes the pointer by reference, the second by value.
If you use the first signature, you can modify both the memory the pointer points to, as well as which memory it points to.
For example:
void printR(int*& pointer) //by reference
{
*pointer = 5;
pointer = NULL;
}
void printV(int* pointer) //by value
{
*pointer = 3;
pointer = NULL;
}
int* x = new int(4);
int* y = x;
printV(x);
//the pointer is passed by value
//the pointer itself cannot be changed
//the value it points to is changed from 4 to 3
assert ( *x == 3 );
assert ( x != NULL );
printR(x);
//here, we pass it by reference
//the pointer is changed - now is NULL
//also the original value is changed, from 3 to 5
assert ( x == NULL ); // x is now NULL
assert ( *y = 5 ;)
Upvotes: 5
Reputation: 18915
The first passes the pointer by reference. If you pass by reference the function can change the value of the passed argument.
void print(int* &pointer)
{
print(*i); // prints the value at i
move_next(i); // changes the value of i. i points to another int now
}
void f()
{
int* i = init_pointer();
while(i)
print(i); // prints the value of *i, and moves i to the next int.
}
Upvotes: 0