1.交换两个变量的值
#include <stdio.h>
void swap(int *pa, int *pb);
int main(void)
{
int a = 5, b = 6;
swap(&a, &b);
printf("a=%d, b=%d\n", a, b);
return 0;
}
void swap(int *pa, int *pb)
{
int t = *pa;
*pa = *pb;
*pb = t;
}
2.函数返回多个值,某些值只能通过指针返回
#include <stdio.h>
void minmax(int a[], int len, int *max, int *min);
int main()
{
int a[] = {1, 2, 3, 4, 5, 6};
int min,max;
minmax(a, sizeof(a)/sizeof(a[0]), &max, &min);
printf("max=%d, min=%d\n", max, min);
return 0;
}
void minmax(int a[], int len, int *max, int *min)
{
int i;
*min = *max = a[0];
for ( i=1; i<len; i++) {
if ( a[i] < *min) {
*min = a[i];
}
if ( a[i] > *max) {
*max = a[i];
}
}
}
3.函数返回运算的状态,结果通过指针返回
#include <stdio.h>
int divide(int a, int b, int *result);
int main(void)
{
int a = 5;
int b = 2;
int c;
if (divide(a, b, &c)) {
printf("%d/%d=%d\n", a, b, c);
}
return 0;
}
int divide(int a, int b, int *result)
{
int ret = 1;
if ( b == 0 ) {
ret = 0;
} else {
*result = a / b;
}
return ret;
}