I need to concat an undefined number of strings, so I created a function called concat. I need to use va_list structures, but I have a problem while using va_arg macro. This is the code:
Code: Select all
char * concat(const char * str1, const char * str2, ...) {
/* Create argument list */
/* args */ va_list args;
/* argn */ int argn = 2;
/* Start argument list */
va_start(args, str2);
/* Get the lenght of all the strings */
int bufsize = strlen(str1) + strlen(str2);
while(/* -- what? -- */) {
/* Update the buffer size */
bufsize += strlen(va_arg(args, char *));
/* Advance the argument counter */
argn++;
}
/* Add two bytes more for each argument */
bufsize += argn*2;
/* Create the buffer */
char buffer[bufsize];
memset(buffer, 0, bufsize);
/* Copy to it the two initial strings */
strcpy(buffer, str1);
strcat(buffer, str2);
/* Restart the arguments list */
va_start(args, str2);
while(/* -- what? -- */) {
/* Concat the string to the buffer */
strcat(buffer, va_arg(args, char *));
}
/* Close the arguments list */
va_end(args);
/* End the buffer */
buffer[bufsize] = '\0';
/* Return the concatenation */
return buffer;
}
Yes, I can use a temporal buffer; I can copy to it the argument obtained with va_arg and then, gets its longer after checking if is NULL, but... how long should I make that temporal buffer? A macro that indicates maximum lenght of strings? Nah, I want a clean, fast and low-memory-use function.
Can you help me, please?
Thanks everybody!