Thread: use of strtof()

  1. #1
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300

    use of strtof()

    I was going to help this person, and in the course of writing a short demo realized I had not used strtof before and to my horror, am suddenly dumbfounded.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
            float X;
            const char fnum[]="13.666";
    
            X=strtof(fnum,NULL);
            perror("strtof");
            printf("%s\n%f\n",(char*)fnum,X);
    
            return 0;
    }
    Which on my system yields:

    strtof: Success
    13.666
    1096460288.000000


    Where's the catch???
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  2. #2
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    I'm guessing you are using gcc. If you compile that with gcc -Wall it will say something like: "Warning implicit declaration of strtof". If you compile with gcc -std=c99, the function will start working. strtof is c99 only.

  3. #3
    Registered User Maz's Avatar
    Join Date
    Nov 2005
    Location
    Finland
    Posts
    194
    If you compile with -Wall, do you get warning about implicit declaation? It may be that strtof() is not in stdlib.h
    => compiler expects it to return an int, and things get messy. (I do not know though, just guessing )

    Also strtof() came with c99 if I'm not wrong, perhaps you should have some compiler flags turned on?

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Thanks people. I usually use -Wall, and according to GNU strtof() is in stdlib.h. They are correct; the reason for that warning (AFAIK) is to remind you that the function is non-standard. If you're writing stuff for a gnu system and want out of the warning, you can include the prototype for the function and gcc will shut up.

    -std=c99 did it. I guess I have to finish my other post now...
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed