You may want to consider the following commented code (live here on Ideone.com).
In summary:
- Iterate through the input string array, computing the total length of the resulting string, summing the lengths of the input strings, using
strlen().
- Allocate memory for the resulting string, using
malloc().
- Iterate through the input array again, concatenating the input strings, using
strcat().
#include <stdio.h> /* For printf() */
#include <stdlib.h> /* For malloc(), free() */
#include <string.h> /* For strcat(), strlen() */
/*
* Concatenates input strings into a single string.
* Returns the pointer to the resulting string.
* The string memory is allocated with malloc(),
* so the caller must release it using free().
* The input string array must have NULL as last element.
* If the input string array pointer is NULL,
* NULL is returned.
* On memory allocation error, NULL is returned.
*/
char * ConcatenateStrings(const char** strings)
{
int i = 0; /* Loop index */
int count = 0; /* Count of input strings */
char * result = NULL; /* Result string */
int totalLength = 0; /* Length of result string */
/* Check special case of NULL input pointer. */
if (strings == NULL)
{
return NULL;
}
/*
* Iterate through the input string array,
* calculating total required length for destination string.
* Get the total string count, too.
*/
while (strings[i] != NULL)
{
totalLength += strlen(strings[i]);
i++;
}
count = i;
totalLength++; /* Consider NUL terminator. */
/*
* Allocate memory for the destination string.
*/
result = malloc(sizeof(char) * totalLength);
if (result == NULL)
{
/* Memory allocation failed. */
return NULL;
}
/*
* Concatenate the input strings.
*/
for (i = 0; i < count; i++)
{
strcat(result, strings[i]);
}
return result;
}
/*
* Tests the string concatenation function.
*/
int main(void)
{
/* Result of string concatenation */
char * result = NULL;
/* Some test string array */
const char * test[] =
{
"Hello ",
"world",
"!",
" ",
"Ciao ",
"mondo!",
NULL /* String array terminator */
};
/* Try string concatenation code. */
result = ConcatenateStrings(test);
/* Print result. */
printf("%s\n", result);
/* Release memory allocated by the concatenate function. */
free(result);
/* All right */
return 0;
}