3

The output of the below code is 0.0000. What is happening in the code and why the output is 0.0000 or to ask precisely what happens when we type cast the int* to float* and print the de-referenced value in the below code?

int main(){
   int i = 10;
   int *p = &i;
   printf("%f\n", *(float*)p);
   return 0;
}
Suvarna Pattayil
  • 5,136
  • 5
  • 32
  • 59
Venkat
  • 93
  • 1
  • 7
  • 1
    If you wants to correct your code read Digital_Reality's answer. If you were expecting that your code should print `10.0..` then no it is undefined behaviour here is one more link to answer you [In C, if I cast & dereference a pointer, does it matter which one I do first?](http://stackoverflow.com/questions/4634252/in-c-if-i-cast-dereference-a-pointer-does-it-matter-which-one-i-do-first) – Grijesh Chauhan Jan 01 '14 at 07:36
  • Also see http://floating-point-gui.de/formats/fp/ for an introduction to how floating point numbers are typically stored. (Actually, pretty much universally, but the C language does not mandate this.) – Christopher Creutzig Jan 01 '14 at 08:48
  • This violates strict aliasing and invokes undefined behavior. – Siyuan Ren Jan 01 '14 at 09:06
  • @Grijesh Chauhan ur link helped me a lot. – Venkat Jan 01 '14 at 09:40

2 Answers2

4

Did you mean?

printf("%f\n", (float)*p);

Edit: After you clarified your question.

There will be undefined behaviour if you try to convert Int* to float*. Pointer is a address, and int float are stored in memory in different format. so you can not cast it.

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Digital_Reality
  • 4,488
  • 1
  • 29
  • 31
1

The pointer always holds the memory address, which is either 16 bits or 32 bits. You are basically type casting the Memory address which is unusual behavior. And solution to your problem depends upon what are you trying to achieve.

irshad.ahmad
  • 276
  • 3
  • 9
  • 24