c - How to calculate the length of output that sprintf will generate? -
goal: serialize data json.
issue: cant know beforehand how many chars long integer is.
i thought way using sprintf()
size_t length = sprintf(no_buff, "{data:%d}",12312); char *buff = malloc(length); snprintf(buff, length, "{data:%d}",12312); //buff passed on ...
of course can use stack variable char a[256]
instead of no_buff
.
question: there in c utility disposable writes unix /dev/null
? smth this:
#define forget_about_this ... size_t length = sprintf(forget_about_this, "{data:%d}",12312);
p.s. know can length of integer through log ways seems nicer.
since c simple language, there no such thing "disposable buffers" -- memory management on programmers shoulders (there gnu c compiler extensions these not standard).
cant know beforehand how many chars long integer is.
there easier solution problem. snprintf
knows!
on c99-compatible platforms call snprintf null first argument:
ssize_t bufsz = snprintf(null, 0, "{data:%d}",12312); char* buf = malloc(bufsz + 1); snprintf(buf, bufsz + 1, "{data:%d}",12312); ... free(buf);
in older visual studio versions (which have non-c99 compatible crt), use _scprintf
instead of snprintf(null, ...)
call.
Comments
Post a Comment