I have this function that takes a number \$N\$, and \$N\$ C strings, concatenates and returns the result:
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* mystrcat(int count, ...)
{
char** p;
char* result;
char* ptr;
size_t* len_array;
va_list ap;
int j;
size_t total_length;
if (count < 1)
{
return "";
}
va_start(ap, count);
p = malloc(sizeof(char*) * count);
len_array = calloc(count, sizeof(size_t));
total_length = 0;
for (j = 0; j != count; ++j)
{
p[j] = va_arg(ap, char*);
total_length += (len_array[j] = strlen(p[j]));
}
result = malloc(sizeof(char) * (total_length + 1));
ptr = result;
for (j = 0; j != count; ++j)
{
strcpy(ptr, p[j]);
ptr += len_array[j];
}
*ptr = '\0';
va_end(ap);
return result;
}
int main(int argc, char* argv[]) {
puts(mystrcat(5, "Hello", ", ", "world", ", ", "friends!"));
}
As always, please tell me anything that comes to mind.
p = malloc(sizeof(char*) * count);
. Anyone saying otherwise are just mixing in subjective opinions in their review. Some prefer thep = malloc(sizeof(*p) * count)
style (I do) but that's just personal opinions. The two styles are very similar and this is not a common cause for bugs, so it need to be mentioned in a general code review. Similarly subjective: it is good style to writesizeof(char)
in malloc, so that your coding style remains consistent and that the code is self-documenting. \$\endgroup\$