Linux C

#include
#include
#include
char *mkconcat(char **, int);
int main(void) {
char *strings[] = { "jasmin", "is", "a", "nutcracker" };
char *result = NULL;
result = mkconcat(strings, (sizeof(strings) / sizeof(strings[0])));
if(result == NULL) {
fprintf(stderr, "Error - mkconcat == NULL\n");
return 1;
} else {
printf("%s\n", result);
free(result);
}
return 0;
}
char *mkconcat(char **list, int max) {
char *result = NULL;
int i = 0, len = 0;
/* calc. total size needed ... */
for(i = 0; i < max; i++)
len += (strlen(list[i]) + 1);
/* alloc sufficient mem ... */
result = malloc(len * sizeof(char) + 1);
if(result == NULL) {
fprintf(stderr, "Error - mkconcat -> malloc()\n");
return NULL;
}
/* concatenate strings */
for(i = 0; i < max; i++) {
if(strcat(result, list[i]) == NULL) {
fprintf(stderr, "Error - strcat()\n");
return NULL;
}
if(i < (max - 1)) { /* space only inbetween tokens */
if(strcat(result, " ") == NULL) {
fprintf(stderr, "Error - strcat()\n");
return NULL;
}
}
}
return result;
}