Skip to content

Instantly share code, notes, and snippets.

@spaghetti-
Last active December 10, 2015 03:28
Show Gist options
  • Save spaghetti-/4374386 to your computer and use it in GitHub Desktop.
Save spaghetti-/4374386 to your computer and use it in GitHub Desktop.
how to join a list of strings in c (comma separated). surprisingly worked at the first try
char *joinlist(char **list, char *obj, int count)
{
char *str = NULL;
size_t total = 0;
size_t length = 0;
int i;
for(i = 0; i < count; i++){
total += strlen(list[i]);
}
total += count - 1;
str = (char*) malloc(total); //should probably free this sometime
str[0] = '\0';
for(i = 0; i < count; i++){
if(i != count - 1){
strcat(str, list[i]);
strcat(str, obj);
}
else strcat(str, list[i]);
}
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment