C Program to Reverse Array of Strings
Last Updated :
20 Dec, 2018
Given an array of string literals, reverse the array.
Examples:
Input : arr[] = {"Coding", "Never", "Fail", "Me"}
Output : arr[] = {"Me", "Fail", "Never", "Coding"}
Input : arr[] = {"welcome", "to", "geeksforgeeks"}
Output : arr[] = {"geeksforgeeks", "to", "welcome"}
The idea is to create an array of pointers, store string literals in it. To reverse the array, we start from begin and end, and move both pointers toward each other. While moving, we keep swapping pointers.
#include <stdio.h>
#include <string.h>
void PrintArray( char * arr[], int n)
{
for ( int i = 0; i < n; i++) {
printf ( "%s " , arr[i]);
}
}
void ReverseArray( char * arr[], int n)
{
char * temp;
int j = n - 1;
for ( int i = 0; i < j; i++) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
j--;
}
}
int main()
{
char * arr[] = { "Coding" , "never" , "fail" , "me" };
int n = sizeof (arr) / sizeof (arr[0]);
PrintArray(arr, n);
printf ( "\n" );
ReverseArray(arr, n);
PrintArray(arr, n);
return 0;
}
|
Output:
Coding never fail me
me fail never Coding
Share your thoughts in the comments
Please Login to comment...