案例:输入两个数,输出其中的大值与小值;
# include <stdio.h>
int main()
{ void swap(int *p1,int *p2);
int a,b;
int *pointer_1,*pointer_2;
printf("please enter a and b:");
scanf("%d,%d",&a,&b);
pointer_1=&a;
pointer_2=&b;
if(a<b) swap(pointer_1,pointer_2);
printf("max=%d,min=%d\n",a,b);
return 0;
}
void swap(int * p1,int * p2)
{ int temp;
temp=*p1;
*p1=*p2;
*p2=temp;
}
运行结果:
please enter a and b:5,9
max=9,min=5
分析:
- pointer_1和pointer_2是指针变量,作为参数传递到swap函数中时,需要用指针类型(int *)接收。
- 接收后p1的值为&a,p2的值为&b,p1值为a ,p2值为b,将p1和p2交换,此时是a和b的值交换了。p1和pointer_1的值仍为&a,p2和pointer_2的值仍为&b(指针指向并未发生变化)。
区别于基本数据类型:
如果直接把a和b的值传到swap函数中,将swap函数内容修改如下:
void swap(int x,int y)
{ int temp;
temp=x;
x=y;
y=temp;
}
分析:
这样是将a和b的值复制了一份赋值给了x和y,对x和y的值进行交换,交换后并没有将结果返回给主调函数,所以a和b的值并没有改变。
不能企图通过改变指针形参的值而使指针实参的值改变。
若将swap函数修改为:
void swap(int * p1,int * p2)
{ int * temp;
temp=p1;
p1=p2;
p2=temp;
}
分析:
这样写是交换了p1和p2的值,交换后p1指向了b,p2指向了a。但是由于参数传递是单向的,只能从实参传到形参,所以pointer_1和pointer_2的指向没变。