Can I swap pointers using calling a function?

Here's a pointer swapping function:

1
2
3
4
5
6
7
void swap(int *p1, int*p2){
	int *p;
	p=p1;
	p1=p2;
	p2=p;
	return;
}


and I tried to use it to swap two pointers in the main funtion and it doesnt work:

1
2
3
4
5
6
7
8
int main(){
	int a,b;
	int *pointer1, *pointer2;
	scanf("%d,%d",&a,&b);
	pointer1=&a; pointer2=&b;
               swap(pointer1, pointer2);
	printf("\n%d,%d,\n",*pointer1,*pointer2);
}


Ater the execution, the two pointers are still pointing to the original memory location(pointer1=&a; pointer2=&b;), while I expect them to point to the swapped location(pointer1=&b; pointer2=&a;).

My textbook doesn't explain this very well,
Can anybody help?
Last edited on
You never call the swap function, but it doesn't work anyway.The pointers inside the swap function are copies of the pointers that you pass to the function so the original pointers will not be affected. If you instead pass the pointers by reference it will modify the original pointers.
1
2
3
4
5
6
void swap(int*& p1, int*& p2) {
	int *p;
	p=p1;
	p1=p2;
	p2=p;
}
Last edited on
Oh sorry I did call the function in my original code but I made mistake when writing this thread haha. Have edited it.
And in the code you provided, are you swapping the pointer's content by using another set of pointers that points to the location of pointer1 and pointer2?
Last edited on
closed account (D80DSL3A)
And in the code you provided, are you swapping the pointer's content by using another set of pointers that points to the location of pointer1 and pointer2?

If I may (as Peter87 appears to have departed for now).

No. That would be this solution:
1
2
3
4
5
6
7
// passing addresses of pointers by value (pointers to pointers)
void swap(int** pp1, int** pp2) {
	int *p;
	p = *pp1;
	*pp1 = *pp2;// changing which address is pointed to.
	*pp2 = p;
}

Peter87 passed two pointers by reference. This is so the 'values' of the pointers (the addresses pointed to) may be changed within the function. This is for the same reason that we pass any variable type to a function by reference.
He is doing the equivalent of:
1
2
3
4
5
6
7
void swapValues( int& x1, int& x2 )
{
    int x;
    x = x1;
    x1 = x2;
    x2 = x;
}

except with pointers.
Last edited on
there is also a swap function in <algorithm> which you can use

http://www.cplusplus.com/reference/algorithm/swap/
Last edited on
Topic archived. No new replies allowed.