Building a string in C
<p>This seems like a question that would have been asked before, but I couldn't find it. (If you do, please point me there and close this as a duplicate.)</p>

<p>I have C code which works something like this:</p>

<pre><code>printf("some characters");
for (; n &gt;= 0; n--)
{
    printf(", %s", f(n, k));
}
printf("more characters");
</code></pre>

<p>for some variables <code>n</code> and <code>k</code> and function <code>char* f(int n, int k)</code> which are not important here. (<code>n</code> and <code>k</code> are not constant.) I would like to convert the code above to a function which returns a <code>char*</code> rather than simply using <code>printf</code> to display it. (It will ultimately be printed but this lets me do some refactoring and is of course easier to test that way.) Of course I could just create the strings and copy them over character-by-character but surely there is a better (cleaner, faster, more idiomatic) way of doing this.</p>

<p>In my particular application <code>f</code> is a very simple function, sort of a relative of <code>itos</code>, but which is not cacheable in any meaningful way due to <code>k</code>. But I welcome ideas which are good for that case as it may be useful to others in the future.</p>