Why doesn't strtof print the correct 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 the codec (C online compiler) it does not print 1.25 . In the codec, he prints 2097152.000000 . Here is the codeword link

What have I done wrong here?

+5
source share
1 answer

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

Try using the online service with the post-July version of gcc. Or explicitly add the correct declaration:

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

What happens is that without a declaration, the compiler will by default return the type of the returned function to int . Since the function actually returns a float, the float is interpreted as (not converted) to an integer, and then that integer is converted to a float.

A warning is not generated, presumably because -Wall is not included in the compiler options, and / or the C-standard used allows the use of undeclared functions.

+5
source

All Articles