码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-03-18 20:00:52      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

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

#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\n",a,b);
18     swap(&a, &b);
19     printf("a=%d,b=%d\n",a,b);
20     return 0;
21 }

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

 

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

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!