What is the difference between the two functions? Can you show that through an example? Thank you in advance.
One is swapping variables using variables, the other one is doing the same thing just with pointers. I am given that one of them is wrong, but which one and why?
void swap1(int x, int y) {
int temp;
temp = x;
x = y;
y = temp;
}
void swap2(int *p1, int *p2) {
int temp;
temp = *p1;
*p1 = *p2;
*p2 = temp;
}
It has to do with the concepts of pointers. Consider the program below (just added some informative code):
#include <stdio.h>
void swap1(int x, int y) {
printf("swap1 : xaddr = %p yaddr = %p\n", &x, &y);
printf("swap1: %d %d\n", x, y);
int temp;
temp = x;
x = y;
y = temp;
printf("swap1: %d %d\n", x, y);
}
void swap2(int *p1, int *p2) {
printf("swap2 : xaddr = %p yaddr = %p\n", p1, p2);
int temp;
temp = *p1;
*p1 = *p2;
*p2 = temp;
}
int main()
{
int x = 10, y = 20;
printf("main: xaddr = %p yaddr = %p\n", &x, &y);
swap1(x, y);
printf("main after swap1 : %d %d\n", x, y);
swap2(&x, &y);
printf("main after swap2: %d %d\n", x, y);
return 0;
}
The variables x
and y
in the main are residing in the local function stack of the main()
, when swap1
is called just the copy of the values are passed not the actual address where x
and y
are residing. So, swap operation just takes place between the values which are local to swap1
. Whereas in the case of swap2
, the actual address is being passed. So any operations you perform on that address is reflected in main()
also.
Output:
main: xaddr = 0x7ffda2efc05c yaddr = 0x7ffda2efc058
swap1 : xaddr = 0x7ffda2efc02c yaddr = 0x7ffda2efc028
swap1: 10 20
swap1: 20 10
main after swap1 : 10 20
swap2 : xaddr = 0x7ffda2efc05c yaddr = 0x7ffda2efc058
main after swap2: 20 10
It is evident from the output that the address of x
and y
in the main
are different from the swap1
, and the swap operation indeed took place in swap1
, but it is just local to swap1
. Whereas in swap2
, we are operating on the same address, which main
treats as x
and y
, so operations are permanent.