In this article, we will write a C program to reverse an array using pointers. The program walks through the given array, reverses it, and prints the reversed array on the output screen.
Sample Example:
Original Array: 1 2 3 4 5 Reversed Array: 5 4 3 2 1
Before we write the actual program, let’s have a look at pointers in C programming language.
In C programming, a pointer is a variable that stores the memory address of another variable. It is declared by the *
symbol.
For example, int *ptr
declares a pointer of type int
. This means that the pointer *ptr
can hold the memory address of an integer type of variable.
To reverse an array using pointers in C, we can use the following algorithm:
- Initialize two pointers
*start
and*end
of the same data type as of the array. - Initially, assign the array itself to the pointer
*start
so that it can point to the first element of the array. - Add the (size of the array – 1) to the array and assign it to the pointer
*end
so that it can point to the last element of the array. - Run a while loop until the pointers
*start
and*end
point to the same address. - Inside the while loop, swap the elements pointed to by
*start
and*end
. - Increment
*start
by 1 so that it can point to the next element of the array and decrement*end
by 1 so that it can point to the previous element of the array in each iteration of the while loop. - Continue the while loop until
*start
becomes equal to*end
.
Here is the implementation of the above algorithm:
// C Program to reverse an array using pointers #include <stdio.h> int main() { // Initialize the array int arr[] = {1, 2, 3, 4, 5}; int *start, *end, temp; // Calculate the size of the array int length = sizeof(arr)/sizeof(arr[0]); printf("Original Array: "); for(int i = 0; i < length; i++){ printf("%d ", arr[i]); } start = arr; // Points to first element of array end = arr + (length - 1); // Points to last element of array // Reverse the array while(start < end){ // Swap items stored at *start and *end temp = *start; *start = *end; *end = temp; start++; // Move to next address end--; // Move to previous address } printf("\nReversed Array: "); for(int i = 0; i < length; i++){ printf("%d ", arr[i]); } return 0; }
Output:
Original Array: 1 2 3 4 5 Reversed Array: 5 4 3 2 1
You have to make sure that the data type of the pointers should also be same as the array itself. For example, if you have an array of char
type, the pointers should also be of char
data type.
I hope you will find this article helpful. Thanks for reading!