>I'm allocating a lot of space, this is a little bit exagerous, maybe there is a way to allocate the correct space I need, something like, sizeof all the parameters?
Since the function doesn't know ahead of time how many parameters there are or what size they are, this is not really possible unless you also pass the total size along as a parameter as well. However, you can realloc your memory for every new parameter that va_arg returns.
>while(s = va_arg(ap,char*)) {
This won't work as you expect, if there's no argument to return, the result is undefined. So you must have a way to tell how many arguments there are:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
char *join (int n_arg, char ch, ...) {
char *buf = NULL, *hold,*s;
int i = 0, j = 0;
va_list ap;
va_start(ap,ch);
while(n_arg-- > 0) {
s = va_arg(ap, char *);
hold = realloc ( buf, i + strlen ( s ) + 2 );
if ( hold == NULL )
; /* Handle the error */
buf = hold;
for (j = 0; s[j]; j++)
buf[i++] = s[j];
buf[i++] = ch;
}
buf[--i] = '\0'; //delete the last ':' occurence and add \0
return buf;
}
int main(void) {
char *test;
test = join(4,':',"lele","loli","loaaa","sshshsh");
printf("%s\n",test);
free(test);
return 0;
}
C isn't as flexible as Perl when it comes to strings, and the Perl string mechanism is far more complex than a simple nul terminated array, so don't expect as convenient a solution unless you're willing to define your own strings like Perl does.
-Prelude