/ Published in: C
Concatenate a list of strings into a dynamically allocated string.
Expand |
Embed | Plain Text
#include <stdlib.h> #include <string.h> #include <stdarg.h> /* vstrconcat() - return a newly allocated string that is the concatenation of all the string passed in the variable length argument list. The argument list *must* be terminated with a NULL pointer. All other arguments must be char* to ASCIIZ strings. Thre return value is a pointer to a dynamically allocated buffer that contains a null terminated string with all the argument strings concatenated. The returned pointer must be freed with the standard free() function. */ char* vstrconcat( char const* s1, ...) { size_t len = 0; char const* src = NULL; char* result = NULL; char* curpos = NULL; va_list argp; if (!s1) { return NULL; // maybe should return strdup("")? } // determine the buffer size needed src = s1; va_start(argp, s1); while (src) { len += strlen(src); //TODO: protect against overflow src = va_arg(argp, char const*); } va_end(argp); result = malloc(len + 1); if (!result) { return NULL; } // copy the data src = s1; va_start(argp, s1); curpos = result; while (src) { size_t tmp = strlen(src); memcpy(curpos, src, tmp); curpos += tmp; src = va_arg(argp, char const*); } va_end(argp); result[len] = '\0'; return result; } /* strconcat() - simple wrapper for the common of concatenating exactly two strings into a dynamically allocated buffer */ char* strconcat( char const* s1, char const* s2) { return vstrconcat( s1, s2, NULL); }
You need to login to post a comment.
