C++数组逆置while循环指针
时间: 2024-09-13 19:13:18 浏览: 64
在C++中,如果你想要通过while循环和指针来逆序一个数组,可以使用两个指针,一个指向数组的开始(end - n),另一个指向数组的结束(end)。这里假设`n`是数组的长度:
```cpp
#include <iostream>
void reverseArray(int arr[], int size) {
int start = 0; // 指向数组开头
int end = size - 1; // 指向数组结尾
while (start < end) { // 当start小于end时继续循环
// 交换当前位置的元素
std::swap(arr[start], arr[end]);
// 移动指针
start++;
end--;
}
}
// 示例
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
std::cout << "Original array: ";
for (int i : arr) {
std::cout << i << " ";
}
reverseArray(arr, size);
std::cout << "\nReversed array: ";
for (int i : arr) {
std::cout << i << " ";
}
return 0;
}
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)