#include <stdio.h>
void
swap(
int
* p3,
int
* p4);
int
main()
{
int a = 9;
int
b = 8;
int
* p1 = &a;
int
* p2 = &b;
printf
(
"%x %x\n"
,p1,p2);
swap(p1,p2);
printf
(
"%d %d\n"
,a,b);
printf
(
"%d %d\n"
,*p1,*p2);
printf
(
"%x %x\n"
,p1,p2);
return
0;
}
void
swap(
int
* p3,
int
* p4)
{
int
* t;
t = p3;
p3 = p4;
p4 = t;
}
|
Beginner C's pointer type, will certainly write such a program, is the use of functions to exchange two values.
The above code is also very easy to think of, but the result of this code is wrong!!! The reason is that a function cannot have more than one return value!!
If more than one value is to be returned, use the method of upward communication (that is, the address of the argument as the variable).
In the process of single-step debugging, we can also see that the two times the address has not changed.
If you use single-step debugging, you can see that the values of P3 and P4 have indeed changed, meaning that the memory that P3 and P4 point to is indeed exchanged, but this exchange does not affect the memory that the P1 and P2,p1 and P2 point to are not changed.
It is equivalent to swapping the swap function only for the value of the address stored in the P3 and P4.
PS: In the direct operation of the address (pointer), you can think of the int * as a whole int, then the change in the P3,P4 is equivalent to the change of two int type variable, the variable of int in the called function will not be brought back to the main function without the return value. However, if you use a return value, but you cannot bring back two values, use the pointer type.
On the problem of the transfer value of the SWAP function