We can observe this using the memory stack. First main() is pushed onto the stack, then mystery(&a,&b) is pushed onto the stack.
Now in the mystery function the addresses gets swapped. After the end of the function ptra points at 0 and ptrb at 2016. BUT these addresses are lost as when mystery is popped out and control goes back to main.
ptra and ptrb are local to the function only. had it been the case that we change the values at the memory locations then the change would have been permanent.
#include <stdio.h>
void mystery (int *ptra, int *ptrb) {
int *temp;
printf("1.Values are *ptra : %d\t*ptrb:%d\n",*ptra,*ptrb);
printf("Values are ptra : %d\tptrb:%d\n",ptra,ptrb);
temp = ptrb;
ptrb =ptra;
ptra = temp;
printf("2.Values are *ptra : %d\t*ptrb:%d\n",*ptra,*ptrb);
printf("Values are ptra : %d\tptrb:%d\n",ptra,ptrb);
}
int main () {
int a = 2016, b=0, c= 4, d = 42;
printf("Address of a is %d \tValue of a is %d\n",&a,a);
printf("Address of b is %d \tValue of b is %d\n",&b,b);
mystery (&a, &b);
printf("Address of a is %d \tValue of a is %d\n",&a,a);
printf("Address of b is %d \tValue of b is %d\n",&b,b);
if (a < c)
mystery (&c, &a);
mystery (&a, &d);
printf("Value of a is %d\n", a);
}
Output is
Address of a is 1724577616 Value of a is 2016
Address of b is 1724577620 Value of b is 0
1.Values are *ptra : 2016 *ptrb:0
Values are ptra : 1724577616 ptrb:1724577620
2.Values are *ptra : 0 *ptrb:2016
Values are ptra : 1724577620 ptrb:1724577616
Address of a is 1724577616 Value of a is 2016
Address of b is 1724577620 Value of b is 0
1.Values are *ptra : 2016 *ptrb:42
Values are ptra : 1724577616 ptrb:1724577628
2.Values are *ptra : 42 *ptrb:2016
Values are ptra : 1724577628 ptrb:1724577616
Value of a is 2016
Memory Model