Problem in pointers

i am trying to interchange the address of two pointers by the following code but this code doesn't change them. please tell me why is it happening and how to change it?

but when i uncomment the commented statements then it happens?

#include <iostream>

using namespace std;

void exchange ( int *ptr_a, int *ptr_b ) {
int *t;

t = ptr_a;

ptr_a = ptr_b;

ptr_b = t;
}

int main()
{
int x;
int y;
int *ptr_x;
int *ptr_y;

ptr_x = &x;
ptr_y = &y;

cout << "Address of ptr_x = " << ptr_x << " & ptr_y = " << ptr_y << endl;
/*
int *t;
t = ptr_x;
ptr_x = ptr_y;
ptr_y = t;
*/

exchange (ptr_x, ptr_y);

cout << "Address of ptr_x = " << ptr_x << " & ptr_y = " << ptr_y << endl;

return 0;
}
You are passing copies of the pointers and the exchange function is swapping the copies.

You need

 
void exchange( int** ptr_a, int** ptr_b ) {}


or better still

 
void exchange( int*& ptr_a, int*& ptr_b ) {}


if you are familiar with references.

BTW, there is already a function called swap() that will do this for you.
u r trying to change the adress of two pointers ???
or adress containig in that pointers????
Topic archived. No new replies allowed.