What is the method for reversing a one-dimensional array in the C language?
To reverse a one-dimensional array in C, you can use two pointers. Start by defining a pointer that points to the beginning of the array and another pointer that points to the end. Swap the elements they are pointing to, then move both pointers towards each other until they meet. Here is an example code:
#include <stdio.h>
void reverseArray(int arr[], int size) {
int *start = arr; // 指向数组开头的指针
int *end = arr + size - 1; // 指向数组末尾的指针
while (start < end) {
// 交换两个指针所指向的元素
int temp = *start;
*start = *end;
*end = temp;
// 移动两个指针
start++;
end--;
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = 5;
reverseArray(arr, size);
// 打印逆置后的数组
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
return 0;
}
By running the above code, the output will be 5 4 3 2 1, which is the result of reversing the array.