Write a C Program To Reverse an Array Using Pointers
In this tutorial, we are going to see how to write a C program to reverse an array using pointers. For example, if ‘arr’ is an array of integers with three elements such as:
arr[0] = 1 arr[1] = 2 arr[2] = 3
Then, by reversing the array we will have:
arr[0] = 3 arr[1] = 2 arr[2] = 1
There are four ways to reverse an array in C, by using for loop, pointers, recursion, or by creating a function.
Write a C Program To Reverse an Array Using Pointers
#include <stdlib.h>
int main(){
int tmp,size,i,j,*arr;
printf("Enter size of array:");
scanf("%d",&size);
//allocates memory depending on size
arr=calloc(sizeof(int),size);
printf("Enter elements in array: ");
for(i=0;i<size;i++)
scanf("%d",arr+i);
for(i=0,j=size-1;i<j;i++,j--){
//swap the elements
tmp=*(arr+i);
*(arr+i)=*(arr+j);
*(arr+j)=tmp;
}
printf("After reversing the array: ");
for(i=0;i<size;i++)
printf("%d ",*(arr+i));
return 0;
}
Output:
Enter size of array: 3 Enter elements in array: 1 2 3 After reversing the array: 3 2 1





