Skip to main content
2 of 2
added 331 characters in body
chux
  • 33.7k
  • 2
  • 38
  • 92

Side issue

"%f" does not well express the state of a floating point (FP) object

When a FP is large, printing 100s of digits is not informative. More compact options exist.

Worse, when a FP is much smaller than 1, "%f" only retains a few or zero digits - losing perhaps all precession.

As FP are encoded in exponential notation, use an exponential format

printf("%a", fp);  //Hexadecimal significant with binary exponent
// or 
printf("%.*e", DBL_DECIMAL_DIG - 1, fp);  // Decimal exponential
// or 
printf("%.*g", DBL_DECIMAL_DIG, fp);  // Decimal exponential when needed, else fix point.

ref


Minor

snprintf() returns an int.

Capture result with an int which may be negative due to "negative value if an encoding error occurred."

int ilen = snprintf(....
if (ilen < 0) return NULL; // or some other error indication.

size_t size = ilen + 1u;
char* buff = malloc(size);
...
chux
  • 33.7k
  • 2
  • 38
  • 92