I am trying to swap the address of two variables from the main function. But address is only swapped inside the function and it does not affect the same variables in the main function. How do I swap the original variables' addresses?
#include<iostream>
usingnamespace std;
void swapAddress(int *&x, int *&y)//*&x is a reference to an integer pointer.
{
cout << "@@Before Address(x) :" << x << endl;
int *temp = x;
x = y;
cout << "@@After Address(x) :" << x << endl;
y = temp;
//The address of x and y are swapped in this function but is not affected outside the scope of this function.
}
int main ()
{
int a = 1;
int b = 2;
int *apointer= &a, *bpointer=&b;
cout << "Before Address(a) :" << &a << endl;
cout << "Before Address(b) :" << &b << endl;
swapAddress(apointer, bpointer);
cout << "After Address(a) :" << &a << endl;
cout << "After Address(b) :" << &b << endl;
return 0;
}
You cannot move a variable in memory. Once a variable is created it stays where it is for its entire lifespan.
The closest you can do to what you are attempting is to copy the variable to a different variable (ie, swap the contents of a and b, rather than their addresses)
int a = 1; // let's say 'a' is put at address 0
int b = 2; // and 'b' is put at address 4
// THEY WILL BE AT THIS ADDRESS FOREVER. You cannot change that.
// memory at this point:
// 0 4 8 C <- address
// +====+====+====+====+
// | 1 | 2 | ? | ? | <- contents
// +====+====+====+====+
// ^ ^
// | |
// a b
// 'apointer' is put at address 8... contains the address of 'a'
// and 'bpointer' is at address C... and contains the address of 'b'
int *apointer= &a, *bpointer=&b;
// memory at this point:
// 0 4 8 C <- address
// +====+====+====+====+
// | 1 | 2 | 0 | 4 | <- contents
// +====+====+====+====+
// ^ ^ ^ ^
// | | | bpointer
// a b apointer
cout << "Before Address(a) :" << &a << endl; // <- these will print the address of 'a', as expected
cout << "Before Address(b) :" << &b << endl; // <- and the address of 'b', as expected
swapAddress(apointer, bpointer); // <- this will swap the contents of apointer and bpointer
// note this does not move any variables... it merely changes the contents of the variables:
// memory at this point:
// 0 4 8 C <- address
// +====+====+====+====+
// | 1 | 2 | 4 | 0 | <- contents
// +====+====+====+====+
// ^ ^ ^ ^
// | | | bpointer
// a b apointer
// | |
// \ /
// \ /
// swapped
Note that all this accomplished was it made 'apointer' point to b, and made 'bpointer' point to a. It did not change 'a' or 'b'.