1、使用临时变量
通过指针方式操作临时变量,从而实现交换两个变更的值。
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
2、使用加法和减法
通过指针传入变量的值,以加法和减法的方式进行交换两个变量的值。
#include <stdio.h>
void swap(int *a, int *b) {
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}
int main() {
int x = 5, y = 10;
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
3、使用异或运算
通过指针传入变量的值,以异或运算的方式进行交换两个变量的值。
#include <stdio.h>
void swap(int *a, int *b) {
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
}
int main() {
int x = 5, y = 10;
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
4、使用指针的指针(二级指针)
通过指针的指针传入变量的值,以临时的变量的方式进行交换两个变量的值。
#include <stdio.h>
void swap(int **a, int **b) {
int *temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 5, y = 10;
int *px = &x, *py = &y;
printf("Before swap: x = %d, y = %d\n", *px, *py);
swap(&px, &py);
printf("After swap: x = %d, y = %d\n", *px, *py);
return 0;
}
5、使用算术运算(仅限整数类型)
通过指针传入变量的值,以算术运算的方式进行交换两个变量的值。但仅限整数类型,代码如下,
#include <stdio.h>
void swap(int *a, int *b) {
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}
int main() {
int x = 5, y = 10;
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}