Reputation: 955
Can someone tell me if my understanding is right ? can someone tell me if the code below is for reference to pointers ?
# include <iostream>
using namespace std;
//function swaps references,
//takes reference to int as input args and swap them
void swap(int& a, int& b)
{
int c=a;
a=b;
b=c;
}
int main(void)
{
int i=5,j=7;
cout<<"Before swap"<<endl;
cout<<"I:"<<i<<"J:"<<j<<endl;
swap(i,j);
cout<<"After swap"<<endl;
cout<<"I:"<<i<<"J:"<<j<<endl;
return 0;
}
Upvotes: 2
Views: 1599
Reputation: 2271
I would like to supplement everybody's answers with the standard conforming solution. It is good to know hot things like these work, but I find it better to use std::swap
. This also has extra specializations a for containers, and it is generic for any type.
I know that this doesn't answer your question, but it is good to at least know that the standard is there.
Upvotes: 0
Reputation: 1426
You can create a reference to a pointer like this.
int i, j;
int* ptr_i = &i; //ptr_i hold a reference to a pointer
int* ptr_j = &j;
swap(ptr_i, ptr_j);
Function should be,
void swap(int*& a, int*& b)
{
//swap
int *temp = a;
a = b;
b = temp;
}
Note that:
a
is the reference for the pointer, ptr_i in the above example.
*a
dereferences what ptr_i
point to, so you get the variable the
pointer, ptr_i
is pointing to.
For more refer this.
Upvotes: 3
Reputation: 96
In order to modify passing variables to a function, you should use reference (C-style pointers could also be a choice). If your objective is to swap pointers (in your case, addresses of the int variables) you should use reference to pointers and also pass to your swap function pointers (addresses of your int variables)
# include <iostream>
using namespace std;
void swap(int* &a, int* &b)
{
int* c=a;
a=b;
b=c;
}
int main(void)
{
int i=5,j=7;
int * p_i = &i;
int * p_j = &j;
cout << "Before swap" << endl;
cout << "I:" << *p_i << "J:" << *p_j << endl;
swap(p_i,p_j);
cout << "After swap" << endl;
cout << "I:" << *p_i << "J:" << *p_j <<endl;
return 0;
}
Upvotes: 1