Piotrne <> writes:
> I have a strange problem with casting addresses to different
> types. I have a float variable. The sequence of 4 bytes
> representing its value should be copied to an int
> (of the same size like float: 4 bytes) and then back
> to the float variable. Example:
>
> #include <stdio.h>
>
> int main(int argc, char **argv)
> {
> float x = 4.3;
> int y;
>
> y = *(int*)&x; /* copying of 4 bytes to int */
> x = *(float*)&y; /* and back to float */
>
> printf("x=%f\n",x); /* 4.3 expected here */
> printf("y=%d\n",y);
> return 0;
> }
Your code is at least non-portable. It assumes, among other things,
that int and float are the same size and that they have similar
alignment requirements. Your system (apparently) happens to satisfy
those assumptions, but others may not.
Even so, the compiler may assume that a float* won't be used to access
an int object, and that an int* won't be used to access a float object.
If you really want to copy the representation of one object into an
object of a different type, use memcpy().
What exactly are you trying to accomplish?
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"