指针实现逆序存放元素技巧解析

指针实现逆序函数

//由于指针表示的是数据存放的地址,而地址是可以比较大小的;
//    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;
}

++++++++++每天的努力就是对未来最大的馈赠++++++++

在这里插入图片描述

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