我正在寻找一个示例代码或者如何改进下面的代码(这是非常慢的IMO,但它是我可以写)以最快的方式: 将2D阵列转换为char*
并将char
复制到它。将2D数组转换为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");
}
任何帮助,对优化建议非常赞赏。提前致谢。
你的标题指出要追加的char的端P该字符串,但在你的代码中,你将char放在每个字符串之间。你想要达到什么目标? – 2012-07-20 20:07:56