C语言交换两个变量的值,用指针方式
程序员文章站
2022-07-03 19:18:37
...
#include<stdio.h>
#include<Windows.h>
//方法一:定义临时变量
void change(int *a,int *b)
{
int c;
c = *a;//相当于 c = a;
*a= *b;//相当于 a = b
*b= c; //相当于 b= c
}
方法二:利用加减法运算
void inplace_swap2(int*a,int*b)
{
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
}
//方法三:利用位运算 (当*x和*y相等时,此方法不可用)
void inplace_swap3(int *x, int *y)
{
*y = *x^*y;
*x = *x^*y;
*y = *x^*y;
}
int main()
{
int a = 6;
int b = 9;
printf("交换之前的a:%d,b:%d\n",a,b);
inplace_swap(&a, &b);
printf("交换之后的a:%d,b:%d\n", a, b);
system("pause");
return 0;
}