写法一、(交换指针指向的地址中存放的数据):
#include<iostream>
usingnamespacestd;
intmain()
{
inta,b,c;
int*p1,*p2,*p3;
inttemp;
cout<<"输入3个整数:"<<endl;
cin>>a>>b>>c;
p1=&a;
p2=&b;
p3=&c;
if(*p1>*p2)
{
temp=*p1;
*p1=*p2;
*p2=temp;
}
if(*p1>*p3)
{
temp=*p1;
*p1=*p3;
*p3=temp;
}
if(*p2>*p3)
{
temp=*p2;
*p2=*p3;
*p3=temp;
}
cout<<'\n'
<<"按由小到大顺序输出:"<<'\n'
<<a<<'\n'
<<b<<'\n'
<<c<<'\n';
return0;
}
写法二、(交换指针指向的地址):
#include<iostream>
usingnamespacestd;
intmain()
{
inta,b,c;
int*p1,*p2,*p3;
int*temp;
cout<<"输入3个整数:"<<endl;
cin>>a>>b>>c;
p1=&a;
p2=&b;
p3=&c;
if(*p1>*p2)
{
temp=p1;
p1=p2;
p2=temp;
}
if(*p1>*p3)
{
temp=p1;
p1=p3;
p3=temp;
}
if(*p2>*p3)
{
temp=p2;
p2=p3;
p3=temp;
}
cout<<'\n'
<<"按由小到大顺序输出:"<<'\n'
<<*p1<<'\n'
<<*p2<<'\n'
<<*p3<<'\n';
return0;
}
写法三、用函数指针
#include<stdio.h>
#include<stdlib.h>
intmain()
{
inta,b,c,*p1,*p2,*p3;
printf("请输入三个整数:");
scanf("%d%d%d",&a,&b,&c);
p1=&a;
p2=&b;
p3=&c;
exchange(p1,p2,p3);
printf("%d%d%d",a,b,c);
return0;
}
voidswap(int*x,int*y)
{
inttemp;
if(*x>*y)
{
temp=*x;
*x=*y;
*y=temp;
}
}
voidexchange(p1,p2,p3)
{
swap(p1,p2);
swap(p1,p3);
swap(p2,p3);
}