对于指针类型的,定义函数,先取得指针的地址,然后在对地址里面的值进行交换,不能直接对地址交换,这是错误的,这样得不到地址里面的值。
#include <stdio.h>
#include <stdlib.h>
void swap_max( int *p1, int *p2);
void main()
{
int *p1,*p2;
int a,b;
printf("please input two number:\n");
scanf("%d %d",&a,&b);
p1 = &a;
p2 = &b;
if(a<b)
{
swap_max(p1,p2);
}
printf("max = %d,min = %d \n",a,b);
}
void swap_max(int *p1,int *p2)
{
int p;
p = *p1;
*p1 = *p2;
*p2 = p;
}
效果
交换地址
#include <stdio.h>
#include <stdlib.h>
void main()
{
int *p1,*p2,*p;
int a,b;
printf("please input two number:\n");
scanf("%d %d",&a,&b);
p1 = &a;
p2 = &b;
if(a<b)
{
p = p1;
p1 = p2;
p2 = p;
}
printf("max = %d,min = %d \n",a,b);
}
三个数比较大小
#include <stdio.h>
#include <stdlib.h>
void main()
{
void swap(int *p1,int *p2);
void exchange(int *p1,int *p2,int *p3);
int *p1,*p2,*p3,temp;
int a,b,c;
printf("please input three numbers:\n");
scanf("%d %d %d",&a,&b,&c);
p1 = &a;
p2 = &b;
p3 = &c;
exchange(p1,p2,p3);
printf("%d>%d>%d \n",*p1,*p2,*p3);
}
void swap(int *p1,int *p2)
{
int temp;
temp = *p1;
*p1 = *p2;
*p2 = temp;
}
void exchange(int *p1,int *p2,int *p3)
{
if(*p1<*p2)
{
swap(p1,p2);
}
if(*p1<*p3)
{
swap(p1,p3);
}
if(*p2<*p3)
{
swap(p2,p3);
}
}