可以通过两种方法将数组逆序存放:
- 使用一个临时数组或者额外的空间来实现数组的逆序存放:
#includevoid reverseArray(int arr[], int size) { int temp; for (int i = 0; i < size / 2; i++) { temp = arr[i]; arr[i] = arr[size - i - 1]; arr[size - i - 1] = temp; } } int main() { int arr[] = {1, 2, 3, 4, 5}; int size = sizeof(arr) / sizeof(arr[0]); reverseArray(arr, size); printf("Reversed Array: "); for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } return 0; }
- 使用指针来实现数组的逆序存放:
#includevoid reverseArray(int *arr, int size) { int temp; int *start = arr; int *end = arr + size - 1; while (start < end) { temp = *start; *start = *end; *end = temp; start++; end--; } } int main() { int arr[] = {1, 2, 3, 4, 5}; int size = sizeof(arr) / sizeof(arr[0]); reverseArray(arr, size); printf("Reversed Array: "); for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } return 0; }