Ben Bacarisse
4/29/2011 4:20:00 PM
pozz <pozzugno@gmail.com> writes:
> I have to create a long string composed by many fields, for example
> integers. I don't know the numbers of fields, so I don't know the
> length of the string.
>
> I think asprintf() could be useful for such thing, so I started
> writing the following code:
>
> char *
> create_string(int *array, size_t asize)
> {
> char *str;
> while(asize--) {
> if (asprintf(&str, "%s %d", str, *array++) < 0) {
> return NULL;
> }
> }
> return str;
> }
>
> I have two doubts here:
> - may I use str for output string and as one of asprintf argument?
> - after the second (the third...), how can I free the previous
> allocated string?
I don't know aprintf well enough (it's non-standard) but I think you'd
have to use a pair of pointers swapping them over and freeing the one
that acted a source each time. Take care with initial conditions!
However, here's another way...
Allocate one string for them all. You don't need more than
const size_t dec_chars = (CHAR_BIT * sizeof(int)) / 3 + 2;
bytes for the decimal representation of an int (including sign). Thus
you can allocate:
asize * dec_chars + asize
bytes for the whole thing (asize - 1 separators plus one for the null).
You can then
size_t position = 0;
for (int i = 0; i < asize; i++) {
position += sprintf(buffer + position,
"%s%d", i ? " " : "", array[i]);
Finally, you can use position to resize the buffer if you feel you need
to. This is a sketch so, you'll have to check the details... I don't
have time to test it.
<snip>
--
Ben.