指針實現逆序存放元素技巧解析

指針實現逆序函數

//由於指針表示的是數據存放的地址,而地址是可以比較大小的;
//    int a[3];
//    int *p1, *p2;
//    p1 = &a[2];
//    p2 = &a[2];
//    printf("%d",(p1 < p2));
//    結果是0;證明c語言確實支持地址比較大小;


#include <stdio.h>
#include <stdlib.h>

swap(int *a, int *b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
    return 0;
}

invert(int *_array, int n)
{
    int *fst = _array;    //頭指針
    int *ed  = (_array + n - 1);    //尾指針
    while(fst < ed)
        swap(fst++,ed--); //每次交換兩個元素之後,移動指針
    return 0;
}

int main()
{
    int n, test[100];
    printf("please input the number of the sequence: ");
    scanf("%d", &n);

    printf("please input %d terms:\n", n);
    for(int i=0; i<n; ++i)
        scanf("%d", &test[i]);
    invert(test, n);

    for(int i=0; i<n; ++i)
        printf("%d ", test[i]);
    return 0;
}

++++++++++每天的努力就是對未來最大的饋贈++++++++

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章