I made a function in C, that concatenates a variable number of strings.
That’s my code:
char* texto(const char* s, ...){
va_list args;
char *tmp;
char *res;
size_t len = strlen(s);
// pega um handle ao início da lista de parâmetros
va_start(args, s);
// calcula o tamanho total de todas as strings - pega o próximo parâmetro da lista, até chegar no NULL
while ((tmp = va_arg(args, char*))){
len += strlen(tmp);
}
va_end(args);
res = malloc(len+1);
if (!res){
fprintf(stderr, "Erro ao alocar string. Função 'texto'\n");
exit(EXIT_FAILURE);
}
// cria a string concatenada
strcpy(res, s);
va_start(args, s);
// pega o próximo parâmetro da lista, até chegar no NULL
while ((tmp = va_arg(args, char*))){
strcat(res, tmp);
}
va_end(args);
return res;
}
I’m using like this:
char* txt = texto("a", "b", "c", "d", "e", NULL);
//txt is now: "abcde"
It works fine.
But I can’t pass numeric parameters to this function, only strings.
I need to change the function to work like this:
char* txt = texto("a", "b", 1, "d", 4.5, "e", NULL);
//txt is now: "ab1d4.5e"
How can I do that?
How I get parameters with diferent types using va_arg()?
The solution I found until now is create a function int2str():
inline char* int2str(int inteiro){
char* str = malloc(10);
sprintf(str, "%d", inteiro);
return str;
}
But I have to use this way:
char* txtnum = int2str(23);
char* txt = texto("a", txtnum, NULL);
free(txtnum);
otherwise, I got a memory leak…
I could use the function int2str() inside the function texto() but I don’t know how to check the type of the parameters!
Ps.: I’m using C, not C++ for my code.
If you’re willing to take a gcc specific solution you can change
int2strto be this macro:This then means you can write:
without leaking. It’s very non portable though.