Wednesday, June 11, 2008

Swap two pointers

Our task is to two pointers which is pointing to two objects. The problem is very simple and remember to use pointer to pointer concept. Without that it is just a pass by value to the function.


#include<stdio.h&gt;
void swap(int **firstPtr, int **secondPtr)
{
int *temp = *firstPtr;
*firstPtr = *secondPtr;
*secondPtr = temp;

return;
}

int main()
{
int a = 10;
int b = 20;

int *aPtr = &a;
int *bPtr = &b;

printf("Before Swapping, Address : %x %x, Value : %d %d\n", aPtr, bPtr, *aPtr, *bPtr);
swap(&aPtr, &bPtr);
printf("After Swapping, Address : %x %x, Value : %d %d\n", aPtr, bPtr, *aPtr, *bPtr);
}

If you compile and see the result, the pointers would be swapped ..

2 comments: