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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Output:

Coding never fail me 
me fail never Coding


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.