I'm looking for an example code or how to improve the below code (that it's very slow IMO, but it's that I can write) to the fastest way to convert an 2D-array into a char* and copy a char to it.
char*
join(int c, size_t arrsize, const char* arr[])
{
char *buf, *tbuf, *val;
size_t i, vsize, total;
buf = malloc(1);
for(i = total = 0; i < arrsize; ++i) {
val = arr[i];
vsize = strlen(val);
if((tbuf = realloc(buf, total + vsize + 2)) == NULL) {
if(buf != NULL)
free(buf);
return NULL;
}
buf = tbuf;
memcpy(buf + total, val, vsize);
total += vsize;
buf[total] = c;
total += 1;
}
buf[total] = '\0';
return buf;
}
calling
const char *foo[] = { "a", "b", "c"};
char *baa = join(' ', 2, foo); //a b c
if(baa) {
printf("%s\n", baa);
free(baa);
} else {
printf("No memory\n");
}
How can this be optimised?
char 2d_array[m][n]and is already layed out aschar array[m*n]which would make this simple - it could even be done in place. What you have is an array of pointers to char, which point to the beginning of '\0' terminated char arrays of unspecified length. BTW on 64 bit its cheaper to use an actual 2d array when all strings are under the size of an 8 byte pointer (up to16 if no strings are repeated). If you do use actual 2d arrays you have to pass around dimensions though.