我正在寻找示例代码或如何改进下面的代码(IMO 非常慢,但这是我可以编写的)以最快的方式将 2D 数组转换为 achar*
并将 a 复制char
到其中。
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;
}
打电话
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");
}
如何优化?