c语言swap函数 c语言swap函数交换数组

c语言中swap是个什么函数?swap函数一般是一个程序员自定义函数,是实现两个变量数值的交换 。
1、比如:
int a = 2;
int b =3;
swap(a,b); //一般用到变量数值交换 , 交换后a=3 b = 2;
2、通过使用临时变量实现交换 。
void swap1(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
}
扩展资料
C语言swap函数的使用
#includestdio.h
void swap(int *pa,int *pb)
{
int temp;
temp=*pa,*pa=*pb,*pb=temp;
}
void main()
{
int a=10,b=20;
swap(a,b);//传递的是实参变量a,b的地址
printf("a=%d,b=%d\n",a,b);
}
c语言中swap 是什么意思?swapc语言swap函数的意思是交换两个变量的值
但是在c语言中没有这样的库函数c语言swap函数 , 需要自己写
写法如下c语言swap函数:
void swap(int *a,int *b)//表示传入指针c语言swap函数,这样就可以修改变量的值
【c语言swap函数 c语言swap函数交换数组】{
int t=*a;*a=*b;*b=t;
}
然后使用方法:
#includestdio.h
void swap(int *a,int *b)
{
int t=*a;*a=*b;*b=t;
}
int main(){
int a,b;
scanf("%d%d",a,b);
swap(a,b);//传入时要传指针,是取址符
printf("a = %d,b = %d\n",a,b);
return 0;
}
输入:2
3
输出a
=
3,b
=
2
C语言中swap的作用和用法1.作用:swap的意思是交换两个变量的值,是一个自定义函数 。
2.用法:使a和b的值进行互换 。
例如:void swap(int*p1,int*p2)//*p1=a;*p2=b;
改变指针指向的地址的值,即a和b的值互换 。
3.其他用法
swap1只进行了值传递,所以函数调用结束后形参被释放,不能实现实参的值交换;
swap2直接使用全局变量,这样swap2函数和main函数操作的是同一个变量(地址和值都一样),可以实现值交换;
swap3使用传地址的方式 , 通过修改内存块来实现变量的值交换 , 是可以的 。
swap4使用引用()的方式,这样是给mian函数中待交换的变量起一个别名,并把把别名作为形参在swap4中进行处理,这其实就实现了形参和实参的地址和内容完全一样 , 当然可以实现值交换,swap4的效果和swap2的一样,但这种定义方式更利于程序的调试和维护 , 同时也可以减小内存开销 。
swap5中虽然也把变量的地址传到了函数中 , 但在函数内部并没用修改地址指向的内存块而是把地址在形参上完成交换,swap5函数运行结束,所有的工作都会都是,而main函数中的变量也没有实现交换,这种情况和swap1类似 。
具体代码如下:
/*-----try to swap the value of a and b, but it does not work out.*/
/*void swap1(int x,int y)
{
int temp;
temp = x;
x = y;
y = temp;
}*/
/*------using the global variables can implement the swap----*/
/*int a(3),b(5);
//the declarations of a and b in the main function should be commented out.
void swap2()
{
int temp;
temp = a;
a = b;
b = temp;
}*/
/*----using the pointer to pass the address to the swap function*/
/*void swap3(int *px,int *py)
{
int temp;
temp = *px;
*px = *py;
*py = temp;
}*/
/*----using the reference operator()-----*/
void swap4(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
/*----meaningless swap---*/
/*void swap5(int *px,int *py)
{
int *p;
p = px;
px = py;
px = p;
}*/
int main(int argc, char* argv[])

推荐阅读