Join a string array into one allocated buffer
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Join 'count' strings with 'sep'; returns a malloc'd buffer or NULL. */
char *join_strings(const char *const *parts, size_t count, const char *sep)
{
size_t total = 1, sep_len = strlen(sep);
for (size_t i = 0; i < count; i++) {
total += strlen(parts[i]) + (i > 0 ? sep_len : 0);
}
char *out = malloc(total);
if (out == NULL) {
return NULL;
}
char *cursor = out;
for (size_t i = 0; i < count; i++) {
if (i > 0) {
memcpy(cursor, sep, sep_len);
cursor += sep_len;
}
size_t part_len = strlen(parts[i]);
memcpy(cursor, parts[i], part_len);
cursor += part_len;
}
*cursor = '\0'; /* total already reserves the trailing NUL */
return out;
}
int main(void)
{
const char *words[] = {"alpha", "beta", "gamma"};
char *line = join_strings(words, 3, ", ");
if (line == NULL) return 1;
puts(line);
free(line);
return 0;
}