Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How large buffer do I need?

Tags:

c

printf

c89

For a double value stored in x, how large does buffer need to be in the function call below?

sprintf(buffer, "%.*g", DBL_DIG, x);
like image 860
August Karlstrom Avatar asked Jan 16 '15 07:01

August Karlstrom


1 Answers

The worst case will be :

  • one minus - if number if negative
  • one decimal point .
  • DBL_DIG decimal digits
  • the exponent part that should not be greater that e+999 (*)
  • the terminating null

So the size of buffer should be DBL_DIG + 8.

(*) According to wikipedia page on [IEEE floating point] the exponent part for a double is at most 21023 < 10308. So the decimal representation of the exponent need at most 3 digits.

Of course above stuff only has sense for IEEE754 compliant floating point implementations (thanks to Basile Starynkevitch for noticing)

like image 62
Serge Ballesta Avatar answered Sep 22 '22 21:09

Serge Ballesta