How to concatenate multiple strings in C
? I have a function for concatenation of two strings (no 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;
}
Is there a way to use this function (or strcat()
) to concatenate multiple strings? Also, is this dynamic allocation right:
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;
}
Yes, you can extend the code from the first function to deal with a whole array:
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;
}
You do not need to allocate temporary 2D structures. Since you can precompute the length of the result, a single allocation is sufficient.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다