1 #include <stdlib.h> 2 #include <stdarg.h> 3 #include <string.h> 4 5 #include "concat-strings.h" 6 concat_strings(const char * first,...)7extern char *concat_strings(const char *first, ...) 8 { 9 va_list rest; 10 size_t len; 11 const char *p; 12 char *result; 13 14 /* calculate length of the new string. */ 15 len = 0; 16 va_start(rest, first); 17 for (p = first; p != NULL; p = va_arg(rest, const char *)) { 18 len += strlen(p); 19 } 20 va_end(rest); 21 22 /* allocate enough memory. */ 23 result = malloc(len + 1); 24 if (result == NULL) { 25 return NULL; 26 } 27 *result = '\0'; 28 29 /* copy the arguments to the new string. */ 30 va_start(rest, first); 31 for (p = first; p != NULL; p = va_arg(rest, const char *)) { 32 strcat(result, p); 33 } 34 va_end(rest); 35 36 return result; 37 } 38