Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does strtof not print proper float?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
  char aaa[35] = "1.25";
  char* bbb = &(aaa[0]);
  char** ccc = &(bbb);
  float a = strtof(*ccc, ccc);
  printf("%f\n", a);
  return 0;
}

The code I wrote above should print 1.25, but according to codepad (online C compiler), it does not print 1.25. On codepad, it prints 2097152.000000 . Here's the codepad link

What have I done wrong here?

like image 350
John Luke Avatar asked Apr 22 '15 04:04

John Luke


1 Answers

codepad has an old version of gcc, and presumably of the standard C library. Apparently, strtof is not being declared by the header files you include. (strtof was added in C99.)

Try using an online service with a postdiluvian version of gcc. Or explicitly add the correct declaration:

float strtof(const char* ptr, char** end_ptr);

What's happening is that without the declaration, the compiler defaults the return type of the function to int. Since the function actually returns a float, the float is being interpreted as (not converted to) an integer, and then that integer is converted to a float.

No warning is produced, presumably because -Wall is not in the compiler options, and/or the C standard being used allows the use of non-declared functions.

like image 54
rici Avatar answered Oct 15 '22 13:10

rici