本實例輸入三個整數 a,b,c,使用指針和交換函數按從小到大排序輸出。
p1=&a, p2=&b, p3=&c。a>b 交換 p1,p2;若 a>c 交換 p1,p3;若 b>c 交換 p2,p3。swap 函數通過指針交換兩整數值。// Created by www.runoob.com on 15/11/9.
// Copyright © 2015年 菜鳥教程. All rights reserved.
//
#include <stdio.h>
void swap(int *, int *);
int main(void) {
int a, b, c;
int *p1, *p2, *p3;
printf("輸入 a, b ,c:\n");
scanf("%d %d %d", &a, &b, &c);
p1 = &a; p2 = &b; p3 = &c;
if (a > b) swap(p1, p2);
if (a > c) swap(p1, p3);
if (b > c) swap(p2, p3);
printf("%d %d %d\n", a, b, c);
}
void swap(int *s1, int *s2) {
int t = *s1;
*s1 = *s2;
*s2 = t;
}
輸入 a, b ,c:
1 3 2
1 2 3
指針交換避免了數值拷貝,邏輯清晰,適合教學指針用法。