C语言指针经典算法应用《指针作为函数参数》
C语言指针经典算法应用《指针作为函数参数》
函数的参数不仅可以是整型、浮点型、字符型等数据,还可以是指针类型。它的作用是将一个变量的地址传送给被调用函数的形参。
#include??<iostream>
using?namespace?std;
int?main()
{
void?swap(int?p1, int?p2);?????//函数声明
//定义指针变量pointer_1,pointer_2,整型变量a,b
int?pointer_1, pointer_2, a, b;
cin? >> a? >> b;
pointer_1? = &a; //使pointer_1指向a
pointer_2? = &b; //使pointer_2指向b
//如果a<b,使pointer_1和pointer_2互换
if?(a? < b)
swap(pointer_1, pointer_2);
cout? << "max=" << a? << ",min=" << b? << endl;//a已是大数,b是小数?
return?0;
}
void?swap(int?p1, int?p2)????????????//函数的作用是将p1的值与p2的值交换
{
int?temp;
temp? = p1;
p1? = p2;
p2? = temp;
}
运行效果如下:
函数的参数不仅可以是整型、浮点型、字符型等数据,还可以是指针类型。它的作用是将一个变量的地址传送给被调用函数的形参。
#include??<iostream>
using?namespace?std;
int?main()
{
void?swap(int?p1, int?p2);?????//函数声明
//定义指针变量pointer_1,pointer_2,整型变量a,b
int?pointer_1, pointer_2, a, b;
cin? >> a? >> b;
pointer_1? = &a; //使pointer_1指向a
pointer_2? = &b; //使pointer_2指向b
//如果a<b,使pointer_1和pointer_2互换
if?(a? < b)
swap(pointer_1, pointer_2);
cout? << "max=" << a? << ",min=" << b? << endl;//a已是大数,b是小数?
return?0;
}
void?swap(int?p1, int?p2)????????????//函数的作用是将p1的值与p2的值交换
{
int?temp;
temp? = p1;
p1? = p2;
p2? = temp;
}
运行效果如下: