/* string.h declares "strlen". */ #include /* stdlib.h declares "malloc" and "exit". */ #include /* stdio.h declares "stderr", "fprintf", and "printf". */ #include 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; }