Last active
February 15, 2021 03:19
-
-
Save begriffs/22d93deb4ca2c0ceaa8f881c2f455b54 to your computer and use it in GitHub Desktop.
Concatenate multiple strings to a freshly allocated result
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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