Array storage in reverse order can be implemented without pointers. As mentioned in
the previous blog, this sharing focuses on pointer implementation.
Code display:
#include <stdio.h>
void fan(int *x,int n);
int main()
{
int i,arr[5],*p=arr; //定义一个数组,再定义指针变量将数组名赋值给指针变量。
printf("The original array:\n");
for(i=0;i<5;i++,p++)
scanf("%d",p);//作输入p即表示每一个数组元素的地址
printf("Output:\n");
p=arr;//再次赋值传递给子函
fan(p,5);
printf("The array has been inverted:\n");
for(p=arr;p<arr+5;p++)
printf("%d ",*p);
printf("\n");
return 0;
}
void fan(int *x,int n)
{
int temp,i;
for(i=0;i<n/2;i++)
{
temp=*(x+i);
*(x+i)=*(x+n-i-1);
*(x+n-i-1)=temp;
}
}
Code analysis is reflected in the code one by one.
for(i=0;i<n/2;i++)
{
temp=*(x+i);
*(x+i)=*(x+n-i-1);
*(x+n-i-1)=temp;
}
This part is the core algorithm, stored in reverse order. It is not easy to come up with this algorithm at the beginning. For me, most of the C language topics are like finding the rules. The algorithm is really hard to think about. If you are interested, you can buy an introduction to the algorithm.