P
pozz
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?
Moreover, how I can free all the allocated space if one of asprintf
return a negative number?
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?
Moreover, how I can free all the allocated space if one of asprintf
return a negative number?