c++用指针交换两个数
时间: 2024-01-04 08:04:37 浏览: 68
可以使用指针来交换两个数,交换过程中需要注意指针的赋值和解引用操作,具体实现如下:
```c++
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// 示例
int main() {
int x = 5, y = 10;
cout << "Before swap: x=" << x << ", y=" << y << endl;
swap(&x, &y);
cout << "After swap: x=" << x << ", y=" << y << endl;
return 0;
}
```
输出结果为:
```
Before swap: x=5, y=10
After swap: x=10, y=5
```
相关问题
c++通过指针交换两个变量的值
可以通过指针交换两个变量的值,代码如下:
```c
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
```
在调用 swap 函数时,将两个变量的地址作为参数传入即可:
```c
int main() {
int a = 1;
int b = 2;
printf("Before swap: a=%d, b=%d\n", a, b);
swap(&a, &b);
printf("After swap: a=%d, b=%d\n", a, b);
return 0;
}
```
输出结果为:
```
Before swap: a=1, b=2
After swap: a=2, b=1
```
如何用指针交换两个数组的内容
可以通过以下代码来用指针交换两个数组的内容:
```c++
void swapArray(int* arr1, int* arr2, int size) {
int* temp = new int[size];
memcpy(temp, arr1, size * sizeof(int));
memcpy(arr1, arr2, size * sizeof(int));
memcpy(arr2, temp, size * sizeof(int));
delete[] temp;
}
```
这里传入了两个数组的指针 `arr1` 和 `arr2`,以及数组的大小 `size`。首先用 `new` 操作符动态分配一个临时数组 `temp`,然后使用 `memcpy` 函数将 `arr1` 的数据复制到 `temp` 中。接着,将 `arr2` 的数据复制到 `arr1` 中,最后将 `temp` 中的数据复制到 `arr2` 中。注意,在交换完成后需要使用 `delete[]` 释放 `temp` 数组的内存空间。