在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
代码: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的值。注意,“*+指针名”是可以改变它所指向的变量的值的。 |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论