c++指针 将长度为size的整型数组逆序。
时间: 2024-04-30 20:17:18 浏览: 22
可以使用如下代码将长度为size的整型数组逆序:
```
void reverse_array(int *arr, int size) {
int *start = arr;
int *end = arr + size - 1;
while(start < end) {
int tmp = *start;
*start = *end;
*end = tmp;
start++;
end--;
}
}
```
这个函数使用指针来实现数组的反转。具体思路是,使用两个指针start和end,分别指向数组的开头和结尾。然后循环遍历数组,每次交换start和end指向的元素,然后将start向后移动,将end向前移动。当start>=end的时候,数组反转完成。
相关问题
5.将一个整型数组逆序存放后并输出。
可以通过以下方式实现:
```
#include <iostream>
using namespace std;
int main()
{
int arr[] = {1, 2, 3, 4, 5}; // 原数组
int n = sizeof(arr) / sizeof(arr[0]); // 数组长度
int temp;
// 逆序交换数组元素
for(int i = 0, j = n - 1; i < j; i++, j--)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// 输出逆序后的数组
for(int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
5 4 3 2 1
```
希望能帮助到你!
用指针将整形数组逆序输出
好的,我明白了,以下是回答:
要将整型数组逆序输出,可以使用指针来实现。具体的实现方法是:先定义两个指针,一个指向数组的起始位置,一个指向数组的末尾位置,然后交换这两个指针所指向的元素,然后让起始位置指针向后移动一个位置,让末尾位置指针向前移动一个位置,再次交换这两个指针所指向的元素,重复这个过程,直到起始位置指针大于或等于末尾位置指针为止。这样就能将整型数组逆序输出。
以下是代码示例:
```
void reverseArray(int* arr, int size) {
int *start = arr, *end = arr + size - 1;
while (start < end) {
int temp = *start;
*start++ = *end;
*end-- = temp;
}
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}
```
使用该函数时,只需要传入整型数组和数组的大小即可,函数会将数组逆序输出。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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://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)