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.
If you compile and see the result, the pointers would be swapped ..
#include<stdio.h>
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 ..
thanx
ReplyDeletethanx
ReplyDelete