Chinaunix首页 | 论坛 | 博客
  • 博客访问: 209670
  • 博文数量: 136
  • 博客积分: 2919
  • 博客等级: 少校
  • 技术积分: 1299
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 09:08
文章分类

全部博文(136)

文章存档

2013年(1)

2011年(135)

我的朋友

分类: C/C++

2011-03-21 19:26:45

  1. /* k&r(5.2): pointers and function arguments
  2.    created on Mar 21, 2011
  3.    */
  4. #include "stdio.h"

  5. void swap1(int, int);
  6. void swap2(int *, int *);

  7. /* main: test pointer as function arguments to swap two ints */
  8. int main()
  9. {
  10.     int i = 3, j = 2, *pi, *pj;
  11.     pi = &i, pj = &j;
  12.     swap1(i, j);
  13. //    swap2(pi, pj);
  14.     printf("i=%d, j=%d\n", i, j);
  15.     return 0;
  16. }

  17. /* wrong version: pass arguments by values */
  18. void swap1(int x, int y)
  19. {
  20.     int temp;
  21.     temp = x;
  22.     x = y;
  23.     y = temp;

  24. }

  25. /* correct version: pass arguments by pointer or address */
  26. void swap2(int *x, int *y)
  27. {
  28.     int temp;
  29.     temp = *x;
  30.     *x = *y;
  31.     *y = temp;

  32. }
阅读(458) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~