题目:用指针作为函数参数实现:输入三个数,按由小到大的顺序输出。
代码:
#include
using namespace std;
int main()
{
void sort(int*, int*, int*);//排序函数声明
int a, b, c;
cout << “please enter 3 integers :” << endl;
cin >> a >> b >> c;
int* p1 = &a;//使p1指向a
int* p2 = &b;//使p2指向b
int* p3 = &c;//使p3指向c
sort(p1, p2, p3);
cout << “sorted order is :” << a << " " << b << " " << c;
return 0;
}
void sort(int* p1, int* p2, int* p3)// 定义排序函数
{
void swap(int*, int*);//声明两数交换函数
if (*p1 > *p2) swap(p1, p2);
if (*p1 > *p3) swap(p1, p3);
if (p2 > p3) swap(p2, p3);
}
void swap(int p1, int p2)//定义交换函数
{
int t = *p1;
*p1 = *p2;
*p2 = t;
}
运行结果
理解指针作为函数参数传递地址。