Program to reverse a string without using the string library

This is an example C program for reversing a string.

#include <stdio.h>
#include <stdlib.h>


/* Reverse the string and put the result into allocated memory. */

char * reverse (const char * string)
{
    int length;
    int j;
    char * r;

    /* Get the length of the string. */

    for (length = 0; string[length]; length++) {
    }

    /* Get memory. */

    r = malloc (length + 1);
    if (! r) {
        fprintf (stderr, "Malloc failed.\n");
        exit (EXIT_FAILURE);
    }
    
    /* Copy the bytes of the string. */

    for (j = 0; j < length; j++) {
        r[j] = string[length - j - 1];
    }
    r[length] = '\0';
    return r;
}



int main (int argc, char ** argv)
{
    int i;

    /* Reverse each string on the command line. */

    for (i = 1; i < argc; i++) {
        const char * string;
        char * r;
        string = argv[i];
        r = reverse (string);
        printf ("The reverse of '%s' is '%s'.\n",
                string, r);

        /* Thanks for the memory. */

        free (r);
    }
    return 0;
}

(download)

The output of the example, when run like

./rs monkey celery madam

looks like this:

The reverse of 'monkey' is 'yeknom'.
The reverse of 'celery' is 'yrelec'.
The reverse of 'madam' is 'madam'.

Related to this, see Example program in C to detect palindromes.


Copyright © Ben Bullock 2009-2017. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com). / Privacy / Disclaimer