如何在C
中连接多个字符串?
我有一个连接两个字符串的函数(没有strcat()
):
char* concat(char *s1, char *s2)
{
char *r, *t;
int d1 = -1, d2 = -1;
while (s1[++d1]);
while (s2[++d2]);
t = r = (char *)calloc(d1 + d2 + 1, sizeof(char));
while (*t++ = *s1++);
t--;
while (*t++ = *s2++);
return r;
}
有没有办法使用这个函数(或strcat()
)来连接多个字符串?
此外,这种动态分配是否正确:
char* concat(char** array, int n)
{
char *r; int i;
r=(char *)calloc(n*MAX+1, sizeof(char));
array=(char **)malloc(n * sizeof(char *));
for(i=0;i<n;i++)
{
array[i]=(char *)malloc(MAX+1);
}
... //concatenation//...
free(r);
free(array[i]);
free(array);
return r;
}
答案 0 :(得分:3)
是的,您可以从第一个函数扩展代码来处理整个数组:
char* concat(char** array, size_t n) {
size_t total = 1; // One for null terminator
for (int i = 0 ; i != n ; i++) {
total += strlen(array[i]);
}
char *res = malloc(total);
char *wr = res;
for (int i = 0 ; i != n ; i++) {
char *rd = array[i];
while ((*wr++ = *rd++))
;
wr--;
}
*wr = '\0';
return res;
}
您无需分配临时2D结构。由于您可以预先计算结果的长度,因此只需一次分配即可。