代码:
void print(int arr[], int n)
{
int i = 0;
for (i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
void reverse(int arr[], int n)
{
int i = 0;
while (i <= ((n - 1) / 2))
{
int tmp = 0;
tmp = arr[i];
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = tmp;
i++;
}
}
#include<stdio.h>
int main(void)
{
int arr[] = { 1,2,3,4,5,6,7,8,9 };
print(arr, sizeof(arr) / sizeof(arr[0]));
reverse(arr, sizeof(arr) / sizeof(arr[0]));
print(arr, sizeof(arr) / sizeof(arr[0]));
return 0;
}
结果:
1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1
分析:
方法二:
(更好)
代码:
void print(int arr[], int n)
{
int i = 0;
for (i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
void reverse(int arr[], int n)
{
int left = 0, right = 0;
for (left = 0, right = n - 1; left <= right; left++, right--)
{
int tmp = arr[left];
arr[left] = arr[right];
arr[right] = tmp;
}
}
#include<stdio.h>
int main(void)
{
int arr[] = { 1,2,3,4,5,6,7,8,9 };
print(arr, sizeof(arr) / sizeof(arr[0]));
reverse(arr, sizeof(arr) / sizeof(arr[0]));
print(arr, sizeof(arr) / sizeof(arr[0]));
return 0;
}
显然这样对下标的计算更加简洁。