Skip to content

Instantly share code, notes, and snippets.

@begriffs
Last active February 15, 2021 03:19
Show Gist options
  • Save begriffs/22d93deb4ca2c0ceaa8f881c2f455b54 to your computer and use it in GitHub Desktop.
Save begriffs/22d93deb4ca2c0ceaa8f881c2f455b54 to your computer and use it in GitHub Desktop.
Concatenate multiple strings to a freshly allocated result
/* concat(0) creates a new "" in heap memory,
and concat(1, foo) is equivalent to strdup(foo).
Note I haven't tested this function yet. */
char *concat(size_t n, ...)
{
va_list ap;
size_t retlen = 0;
char *ret = calloc(1,1);
if (!ret)
return NULL;
va_start(ap, n);
while (n-- > 0)
{
char *s = va_arg(ap, char*);
size_t slen = strlen(s);
char *bigger = realloc(ret, retlen+slen+1);
if (!bigger)
{
free(ret);
return NULL;
}
else
ret = bigger;
strcpy(ret+retlen, s);
retlen += slen;
}
va_end(ap);
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment