Note that there are some explanatory texts on larger screens.

plurals
  1. POConcatenate text with numbers in a function with variable number of parameters
    text
    copied!<p>I made a function in C, that concatenates a variable number of strings. That's my code:</p> <pre><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; } </code></pre> <p>I'm using like this:</p> <pre><code>char* txt = texto("a", "b", "c", "d", "e", NULL); //txt is now: "abcde" </code></pre> <p>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:</p> <pre><code>char* txt = texto("a", "b", 1, "d", 4.5, "e", NULL); //txt is now: "ab1d4.5e" </code></pre> <p>How can I do that? How I get parameters with diferent types using va_arg()?</p> <p>The solution I found until now is create a function int2str():</p> <pre><code>inline char* int2str(int inteiro){ char* str = malloc(10); sprintf(str, "%d", inteiro); return str; } </code></pre> <p>But I have to use this way:</p> <pre><code>char* txtnum = int2str(23); char* txt = texto("a", txtnum, NULL); free(txtnum); </code></pre> <p>otherwise, I got a memory leak...</p> <p>I could use the function int2str() inside the function texto() but I don't know how to check the type of the parameters!</p> <p>Ps.: I'm using C, not C++ for my code.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload