#include <stdio.h>
// 指针 px、py 不变,将两个指针所指内存单元的内容互换
void swap1(int * px , int * py)
{
int tmp = * px ;
* px = * py ;
* py = tmp ;
printf(" * px=%d , * py = %d\n" , * px , * py) ;
}
// 指针 px、py 互换,但两个指针所指内存单元的内容不变
void swap2(int * px , int * py)
{
int * tmp = px ;
px = py ;
py = tmp ;
printf(" * px = %d , * py = %d\n" , * px , * py) ;
}
int main(void)
{
int a = 3 , b = 3 , c = 5 , d = 5 ;
printf("a = %d , c = %d\n" , a , c) ;
swap1(& a , & c) ;
printf("a = %d , c = %d\n" , a , c) ;
printf("b = %d , d = %d\n" , b , d) ;
swap2(& b , & d) ;
printf("b = %d , d = %d\n" , b , d) ;
}
swap() 传入的两个指针就好比传入了两个装有物品的箱子,箱子里面的物品是可以交换的,swap1() 做到了交换两个箱子中的物品,swap2() 只是交换了两个箱子,箱子中的物品并没有变,从函数内部观察,两个函数的交换效果是一样的,但是,从函数外部观察,效果就截然不同了,swap1() 有交换效果,而 swap2() 没有。
编译、运行实况D:\00.Excise\C>cl x.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8804 for 80x86
Copyright (C) Microsoft Corp 1984-1998. All rights reserved.
x.c
Microsoft (R) Incremental Linker Version 6.00.8447
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.
/out:x.exe
x.obj
D:\00.Excise\C>x
a = 3 , c = 5
* px=5 , * py = 3
a = 5 , c = 3
b = 3 , d = 5
* px = 5 , * py = 3
b = 3 , d = 5
D:\00.Excise\C>
|