12.2C语言笔记
指针与函数
例1:中间变量达成数据交换
#include <stdio.h>
void SwapByValue(int*, int*);
int main()
{ int a = 3, b = 4;
SwapByValue(&a, &b);
printf("a=%d,b=%d\n",a,b);
return 0;}
void SwapByValue(int *px, int *py)
{ int tmp;
tmp = *px; *px = *py; *py = tmp;
printf("*px=%d,*py=%d\n", *px, *py);
}
对比(传统方式):
#include <stdio.h>
void SwapByValue(int, int);
int main()
{int a = 3, b = 4;
SwapByValue(a, b);
printf("a=%d,b=%d\n",a,b);
return 0;}
void SwapByValue(int x, int y)
{int tmp;
tmp = x; x = y; y = tmp;
printf("x=%d,y=%d\n", x, y);}
例2:简单计算
#include <stdio.h>
void calculate(int x, int y, int* sum, int* diff)
{
*sum = x + y;
*diff = x - y;
}
int main()
{ int a = 3, b = 4;
int sum, diff;
calculate(a, b, &sum, &diff);
printf("%d和%d的和是:%d\n", a, b, sum);
printf("%d和%d的差是:%d\n", a, b, diff);
return 0;}
|