Reputation: 4365
I am trying to use a reference to pointer to int
like in below program. But I am not getting the expected output.
Output:
9 5
5 9
Expecting:
9 5
9 5
Code:
#include <iostream>
using namespace std;
void swap (int *& a, int *&b)
{
int *t = a;
a = b;
b = t;
}
int main()
{
int a = 5, b = 9;
int *p = &a;
int *q = &b;
swap (p, q);
cout << *p << " " << *q << endl;
cout << a << " " << b << endl;
return 0;
}
Why is my expectation wrong? I head that reference is nothing just an other name of the target variable.
Upvotes: 0
Views: 104
Reputation: 66371
You're swapping the values of the pointers.
Look at this illustration:
First, p
is pointing at a
, q
is pointing at b
:
p a
+---+ +---+
+ ------> | 5 |
+---+ +---+
q b
+---+ +---+
+ ------> | 9 |
+---+ +---+
After you swap p
and q
, q
is pointing at a
, and p
is pointing at b
:
q a
+---+ +---+
+ ------> | 5 |
+---+ +---+
p b
+---+ +---+
+ ------> | 9 |
+---+ +---+
But both a
and b
still have their old values.
Upvotes: 1
Reputation: 56479
I head that reference is nothing just a other name of the target variable
Yes, and target variable in your case is a pointer of the variable, not the variable. Because you're using *
in the function declaration. Then, you're swaping pointers not values.
Use one of these ways:
void swap(int &a, int &b)
{
int t=a;
a=b;
b=t;
}
// ...
int a=5,b=9;
swap(a,b);
or
void swap(int *a, int *b)
{
int t=*a;
*a=*b;
*b=t;
}
// ...
int a=5,b=9;
swap(&a,&b);
Upvotes: 0
Reputation: 31435
In general, you are swapping two pointers and not what they point to.
Maybe your function is confusing you as you are calling the values a and b. Your function swaps two pointers such that the first one now points where the second one was pointing, and the second points to where the first was pointing.
p
was previously pointing to a
and q
to b
. Now p
points to b
and q
points to a
thus your output is 9 5 5 9
There are references in your swap
function. These are references to the pointers, so a
and b
in the function scope become aliases to the parameters passed in, i.e. p
and q
and thus modify p
and q
(to point elsewhere).
Upvotes: 0
Reputation:
In your case, you're swapping the pointers (and not the values). Since you're swapping the pointers, the actual values inside a
and b
remain unchanged. Hencewhy when you print the value of a
, you get 5
and when you print b
you get 9
.
Upvotes: 0
Reputation: 12866
You swap the pointers, not the values. Your expectation is wrong.
Upvotes: 2