what is the best way of passing floats into a string



Hello,
I need to pass a float into a string (o_tail->y). I tried doing:
o_tail->y=malloc(sizeof(float)+1);
snprintf(o_tail->y,sizeof(float)+1,"%f",1.0);

I do not null-terminate as snprintf takes care of this (according to my man page). That's why i also account for the extra +1. However, this only copies 4 bytes. If i have a float number of say -10.0 only -10. would get copied. How do i account for the extra precision? I tried using the format specifier to widen this, but that does not seem to work.

So i tried sprintf (which i'd rather not use because of security implications) and when i do:
o_tail->x=malloc(sizeof(float)+1);
sprintf(o_tail->x,"%f",-10.0);

I get a nice result of -10.000000 in my char * string. Why does it do this. Is it even correct as i do not quite understand this, because i reserved memory for sizeof(float)+1 which should be 5 bytes on my machine, yet it can write -10.000000 (8-9) chars into my char * string. Does sprintf terminate a supplied string "%f %d" as well by the way?

In any case, any insight on this phenomena would be much appreciated.
Kind regards,
-alef

.



Relevant Pages

  • Re: tolower conflict with iostream?
    ... a string will not contain EOF. ... Although the 'is*' and 'to*' account for EOF, ... for negative values of 'char' on platforms where 'char' is a signed ...
    (comp.lang.cpp)
  • Re: How to add thousand separators
    ... First, this code is obsolete as written, because char is a dead data type and should not ... Note that both of these should be stored as string resources since they might need to be ... 18 digits for any reason. ... you have made a VERY SERIOUS DESIGN ERROR. ...
    (microsoft.public.vc.mfc)
  • Re: what is the best way of passing floats into a string
    ... I do not null-terminate as snprintf takes care of this (according to ... But the easiest way to determine the size needed to format a number, ... int length_of_representation(double n,const char* format){ ... I get a nice result of -10.000000 in my char * string. ...
    (comp.unix.programmer)
  • Re: weird problem
    ... I already told you that the comparison between an integer and a float ... to strcmpwhich expects a pointer to a string. ... And now a question about something else: why do you use floating ... int,float, char, etc. ...
    (comp.lang.c)
  • Re: why I can not write to the file after initialize the MFC in a service program
    ... you don't use char, an obsolete data type ... Why do you need an intermedate buffer to write literal strings anyway? ... For example, if AfxWinInit fails, you copy a 45-character string into a ... So you are going to try to initialize MFC EACH TIME THROUGH THE LOOP? ...
    (microsoft.public.vc.mfc)