c语言函数实现交换两个数的值

代码:

 1 #include <stdio.h>
 2 
 3 void swap(int x,int y)
 4 {
 5     int temp;
 6     
 7     temp = x;
 8     x = y;
 9     y = temp;
10     printf("In swap: x = %d,y = %d\n",x,y);
11 }
12 
13 void swap_with_pt(int * x,int * y)
14 {
15     int temp;
16     
17     temp = *x;
18     *x = *y;
19     *y = temp;
20     printf("In swap_with_pt: x = %d,y = %d\n",*x,*y);
21 }
22 
23 int main()
24 {
25     int x = 5,y = 10;
26     
27     printf("Before swap: x = %d,y = %d\n",x,y);
28     swap(x,y);
29     printf("After swap: x = %d,y = %d\n",x,y);
30     printf("-------------------------------\n");
31     printf("Before swap_with_pt: x = %d,y = %d\n",x,y);
32     swap_with_pt(&x,&y);
33     printf("After swap_with_pt: x = %d,y = %d\n",x,y);
34     
35     return 0;
36 }

输出:

1 Before swap: x = 5,y = 10
2 In swap: x = 10,y = 5
3 After swap: x = 5,y = 10
4 ---------------------------------
5 Before swap_with_pt: x = 5,y = 10
6 In swap_with_pt: x =10,y = 5
7 After swap_with_pt: x = 10,y = 5

解释:

      swap函数调用时首先创建x,y的变量副本,我们姑且称之为x2,y2(其实名字依然是x和y,只不过这里的x和y只在swap函数里有意义),并将main函数中x,y的值传给变量x2,y2,然后函数交换了x2,y2的值,运行完函数后x2,y2变量生命期结束。所以,x和y的值是不变的。

      swap_with_pt函数调用时同样创建x,y的指针的变量副本,我们姑且称之为x2,y2(其实名字依然是x和y,只不过这里的x和y只在swap_with_pt函数里有意义),并将x,y的地址值传给x2,y2,这个时候x2和y2是指向main函数中x,y的,然后通过*运算修改x,y的值。注意,“*+指针名”是可以改变它所指向的变量的值的。

c语言函数实现交换两个数的值,布布扣,bubuko.com

c语言函数实现交换两个数的值

上一篇:多线程练习——创建方式2


下一篇:多线程练习——同步之前