1. 程式人生 > >C語言實現陣列逆置

C語言實現陣列逆置

#include <stdio.h>
#include <assert.h>
void swap(int *a ,int *b)
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}
void show(int arr[], int len)
{
    assert(arr);
    assert(len > 0);
    int i = 0;
    for (; i < len; i++){
        printf("%d ", arr[i]);
    }
    printf("\n");
}
 
void reverse(int arr[], int len) { assert(arr); assert(len > 0); int *p = arr; int *q = arr + len - 1; while (p < q){ swap(p, q); p++, q--; } } int main() { int arr[] = {1,2,3,4,5,6,7,8}; int len = sizeof(arr) / sizeof(arr[0]); show(arr, len); reverse(arr, len); show(arr, len);
return 0; }