嵌入式面试 C语言 编写函数把一数组里内容前后颠倒 用指针实现

编写函数把一个数组里所有存储区的内容前后颠倒
加入数组里原有内容是1 2 3 4 5
颠倒后的内容是5 4 3 2 1
用指针编写这个函数

/CSD1702/biaoc/day10 10reverse.c

/*
	指针练习
*/
#include <stdio.h>
int *reverse(int *p_num,int size){	//补充:把数组第一个存储区地址当做返回值使用,不加const关键字
    int *p_head = p_num, *p_tail = p_num + size - 1, tmp = 0;
    while (p_head < p_tail){    //
        tmp = *p_head;		//补充:将头指针和尾指针所捆绑的存储区做交换
        *p_head = *p_tail;
        *p_tail = tmp;
        p_head++;    //交换后前面的地址+1 数字向后移1位
        p_tail--;    //交换后后面的地址-1 数字向前移1位
    }
    return p_num;    //返回数组第一个地址
}
int main(){
    int arr[] = {1,2,3,4,5},num = 0;
    int *p_num = reverse(arr,5);
    for(num = 0;num <= 4;num++){
        printf("%d ",*(p_num + num));
    }
    printf("\n");
    return 0;
}
结果:
5 4 3 2 1

猜你喜欢

转载自blog.csdn.net/u013673437/article/details/88323446