用函数交换两个变量的值(C语言指针)

说道到交换两个变量值,很自然的想到,用第三方变量交换如下:

#include <stdio.h>
 
 int swap(int x,int y)
 {
      int a,b,temp;
       temp=a;
       a=b;
       b=temp;
 }     
 int main()
 {
    swap(a,b);
    printf("a=%d,b=%d",a,b);
 }    

但是如果写在函数中,你调用这个函数,会发现,a和b的值在函数内部交换,当你在mian()中调用这个函数中,发现依然没有交换

这时候就需要用到指针,如下

 1 #include <stdio.h>
 2 
 3 void swap(int *px,int *py)
 4 {
 5     int ptemp;
 6     ptemp=*px;
 7     *px=*py;
 8     *py=ptemp;
 9     
10     
11 }
12 
13 int main(int argc, const char * argv[]) {
14     // insert code here...
15     
16     int a=1,b=2;
17     printf("a=%d,b=%d
",a,b);
18     swap(&a, &b);
19     printf("a=%d,b=%d
",a,b);
20     return 0;
21 }

在外面的函数里面通过指针直接交换传递进去的值,这个可以有,OK,我是这样理解的!

原文地址:https://www.cnblogs.com/chenqingxiao/p/4347791.html