what is the best way of passing floats into a string
- From: atv <alef@xxxxxxxxx>
- Date: Sat, 20 Jan 2007 13:54:19 +0100
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
.
- Follow-Ups:
- Re: what is the best way of passing floats into a string
- From: Pascal Bourguignon
- Re: what is the best way of passing floats into a string
- From: Jens Thoms Toerring
- Re: what is the best way of passing floats into a string
- From: matevzb
- Re: what is the best way of passing floats into a string
- Prev by Date: Re: sem_open/sem_unlink errors
- Next by Date: Re: Random Number Generation on a Linux System
- Previous by thread: sem_open/sem_unlink errors
- Next by thread: Re: what is the best way of passing floats into a string
- Index(es):
Relevant Pages
|