1 #include <iostream> 2 #include<stdio.h> 3 4 using namespace std; 5 6 //起不到交换作用 7 void swap1(int *m, int *n){ 8 int *t; 9 t = m; 10 m = n; 11 n = t; 12 } 13 14 //起到了交换的作用 15 void swap2(int *m, int *n){ 16 int t; 17 t = *m; 18 *m = *n; 19 *n = t; 20 } 21 22 int main() 23 { 24 int a=3,b=5; 25 int *pa = &a; 26 int *pb = &b; 27 28 printf("a=%d, b=%d\n", a, b); 29 30 //交换失败 31 swap1(pa, pb); 32 printf("swap1: a=%d, b=%d\n", a, b);swap1(pa, pb); 33 printf("a=%d, b=%d\n", a, b); 34 35 //交换成功 36 swap2(pa, pb); 37 printf("swap2: a=%d, b=%d\n", a, b); 38 39 return 0; 40 }
结果:
分别执行swap1, swap2函数:(执行一个函数时注释掉另一个函数)