Re: printf("%d",float)



On Oct 30, 8:48 pm, candy_i...@xxxxxxxxx wrote:
Hi all,
I just came across the following program:

#include <stdio.h>
int main()
{
float a = 12.5;
printf("%d\n", a);
printf("%d\n", *(int *)&a);
return 0;
}

The program prints 0 and 1095237362. However, in my opinion it should
print 12 at both the places. Can anybody tell me where I am wrong?

Pointer casting does not convert values of one type to another. Your
code is sort of like this:
struct {
char a;
} A ;
struct {
float b;
} B;
printf("%c", ((A*)&B)->a);
OR
printf("%f", ((B*)&A)->a);
The latter will segfault/crash.
If sizeof(int) != sizeof(float) your code would have *very* likely
crashed. This is one of the reasons why you should be *very* careful
with pointers and never do anything fancy when working with pointers
UNLESS YOU COMPLETELY KNOW WHAT IT DOES, WHY IT DOES THAT, AND ANY
SIDE-EFFECTS. Be very careful, *especially* when you need to pass
void* arguments and struct-cast the pointer to get the data.

Getting back to the different number,
float = [sign bit] [7 exponent bits] [23 mantissa bits]
12.5 = 0 10000010 10010000000000000000000
= 0x41480000
= 1095237632
That's where your number came from.
Source: http://en.wikipedia.org/wiki/Single_precision

.



Relevant Pages

  • Re: Help - buried in compiler warnings.
    ... >> You could allocate the float part in float memory, ... >> int and a float pointer. ... >> You'd have to do horrible unclean things if someone cast a struct ... One possible way is to make unsigned char pointers wide enough to hold ...
    (comp.std.c)
  • Re: Help - buried in compiler warnings.
    ... > struct {int i; float f;} ... int and a float pointer. ...
    (comp.lang.c)
  • Re: struct with pointers
    ... Do I have to freeevery pointer in struc or it it enough to free, ... I want to have a struct representing a table, with int's and float. ...
    (comp.lang.c)
  • Re: struct with pointers
    ... Do I have to freeevery pointer in struc or it it enough to free, ... You must free any pointers in the struct that point to allocated space ... I want to have a struct representing a table, with int's and float. ... int main{ ...
    (comp.lang.c)
  • Re: Help - buried in compiler warnings.
    ... > struct {int i; float f;} ... int and a float pointer. ...
    (comp.lang.c)