Join an array of strings to a single string

This program joins together an array of strings into a single string. It puts the results into allocated memory.

/* string.h declares "strlen". */
#include <string.h>
/* stdlib.h declares "malloc" and "exit". */
#include <stdlib.h>
/* stdio.h declares "stderr", "fprintf", and "printf". */
#include <stdio.h>

const char * array[] = {
    "First entry",
    "Second entry",
    "Third entry",
};

#define n_array (sizeof (array) / sizeof (const char *))

int main ()
{
    int i;
    int total_length;
    char * joined;
    char * end;
    int * lengths;

    /* Allocate memory to store the lengths of the individual
       strings. */

    lengths = malloc (n_array * sizeof (int));
    if (! lengths) {
        fprintf (stderr, "Malloc failed.\n");
        exit (EXIT_FAILURE);
    }

    /* Calculate the total length of all the strings. */ 

    total_length = 0;

    for (i = 0; i < n_array; i++) {
        lengths[i] = strlen (array[i]);
        total_length += lengths[i];
    }

    /* Allocate memory for the joined strings. */

    joined = malloc (total_length + 1);
    if (! joined) {
        fprintf (stderr, "Malloc failed.\n");
        exit (EXIT_FAILURE);
    }
    end = joined;
    for (i = 0; i < n_array; i++) {
        int j;
        for (j = 0; j < lengths[i]; j++) {
            end[j] = array[i][j];
        }
        /* Put the 'end' pointer to the end of the joined string. */
        end += lengths[i];
    }
    /* Put a 'null' character at the end of the string. */
    end[total_length] = '\0';
    printf ("The joined string is '%s'.\n", joined);
    free (lengths);
    free (joined);
    return 0;
}

(download)

The output looks like this:

The joined string is 'First entrySecond entryThird entry'.


Copyright © Ben Bullock 2009-2018. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer