帮我用c++写个使用指针逆置数组
时间: 2024-04-30 11:17:22 浏览: 23
好的,以下是使用指针逆置数组的 C 代码:
```
#include <stdio.h>
void reverseArray(int *array, int length);
int main() {
int array[5] = {1, 2, 3, 4, 5};
int length = sizeof(array) / sizeof(int);
printf("Original array: ");
for (int i = 0; i < length; i++) {
printf("%d ", array[i]);
}
reverseArray(array, length);
printf("\nReversed array: ");
for (int i = 0; i < length; i++) {
printf("%d ", array[i]);
}
return 0;
}
void reverseArray(int *array, int length) {
int *start = array;
int *end = array + length - 1;
while (start < end) {
int temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
```
这段代码定义了一个 `reverseArray` 函数,该函数接受一个整型指针 `array` 和一个整数 `length`,并使用指针操作逆置了该数组。具体来说,该函数定义了两个指针 `start` 和 `end`,分别指向数组的开头和结尾,然后使用一个 while 循环不断交换 `start` 和 `end` 指向的元素,直到整个数组被逆置。在 main 函数中,我们测试了该函数并输出了原始和逆置后的数组。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)