View Single Post
Old Feb 4th, 2007, 11:23 PM   #4
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 6,453
Rep Power: 10 DaWei is on a distinguished road
Why would you declare t as an int? You're swapping int pointers. Since you want persistent effects (I imagine), you need to pass pointers to the pointers to swap, since copies will simply go out of scope when the function returns.

Note that a and b are not swapped, despite what the printf SAYS, only the pointers are swapped.
#include <stdio.h>

void pSwap (int **a, int **b)
{
	int *temp = *a;
	*a = *b;
	*b = temp;
}

int main ()
{
	int a = 4;
	int b = 6;
	int *pA = &a;
	int *pB = &b;

	printf ("a: %d , b: %d\n", *pA, *pB);

	pSwap (&pA, &pB);
	printf ("(swapped) a: %d , b: %d\n", *pA, *pB);
}
Quote:
Originally Posted by Output
a: 4 , b: 6
(swapped) a: 6 , b: 4
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code.
Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers
DaWei is offline   Reply With Quote