Open In App

C Program to Reverse Array of Strings

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.




// C program to reverse an array of strings
#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;
  
    // Move from begin and end. Keep
    // swapping strings. 
    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
Article Tags :