When we learn the pointers, we know that each number in memory occupies a certain byte, that is, the address, only take the address symbol &, so to exchange two number must be the corresponding memory of the two numbers swap, such as a=2;b=3; to make them interchangeable and output, let's try a function.
1#include"stdio.h"2 intTempintXinty)3 {4 intC;5C=x;6x=y;7y=C;8 }9 voidMain ()Ten { One intb; AA=2; -b=3; - Temp (A, b); theprintf"A=%d,b=%d", A, b); -}
Obviously, this method does not, it is only on the surface interchange a A, a, and the function is only in memory when running, when the end, the function of memory is removed, let us look at a more misleading example:
1#include"stdio.h"2 intTempintXinty)3 {4 int*p,*q,t;5p=&x;6q=&y;7t=*p;8*p=*Q;9*q=T;Ten } One voidMain () A { - intb; -A=2; theb=3; - Temp (A, b); -printf"a=%d,b=%d", A, b); -}
The above function uses pointers, why or not? In fact, similar to the previous example, the main function in main () called the temp (A, A, b) passed as an argument to the int temp (int x,int y) parameter passed the value 2, 3; not a A, B address, and then take the address of 2,3, the result is 2,3 address interchange, however a =2,b=3 is still the same, next look at the right is an example:
1#include"stdio.h"2 intTempint*p,int*q)3 {4 intT;5t=*p;6*p=*Q;7*q=T;8 }9 voidMain ()Ten { One intb; AA=2; -b=3; -Temp (&a,&b); theprintf"A=%d,b=%d", A, b); -}
Run Result: The actual argument is temp (&a,&b); Swap the address of a, B.
C: Some misconceptions about pointer function