I am learning C on my own. This is not an assignment. I am trying to implement a function that takes a variable numbers of strings and concatenate them in a new string. It works, but I feel it is not elegant and would like to improve it.
For instance, I don't like how I am using n nor having to decrement argc twice, and I don't like having to use both length
and total_length
. On a more general level, I would like to know if there is a way to parse the variable arguments only once, although it does not seem to be possible unless allocating a fixed number of character or calling malloc
multiple times (which I want to avoid).
/*
* concat_strings - concatenate a variable number of strings
* usage:
* const *message = concat_strings(4, "Error running", argv[0], " - ", "Action create: needs name and email");
*/
char *concat_strings(int argc, ...)
{
va_list ap;
/* calculate the total number of characters in all the strings */
va_start(ap, argc);
int n = argc;
int l = 0;
while(n--)
l += strlen(va_arg(ap, char*));
va_end(ap);
/* allocate memory */
const size_t sizeof_char = sizeof(char);
char *joined = malloc(sizeof_char * (l + 1));
/* copy strings to destination */
va_start(ap, argc);
size_t length = 0;
size_t total_length = 0;
char *s;
while(argc--) {
s = va_arg(ap, char*);
memcpy(joined + total_length, s, sizeof_char * (length = strlen(s)));
total_length += length;
}
*(joined + total_length) = '\0';
va_end(ap);
return joined;
}