In C, you can cast both simple data types like int
, float
, and pointers to these.
Now I would have assumed that if you want to convert from a pointer to one type to the value of another type (e.g. from *float
to int
), the order of casting and dereferencing does not matter. I.e. that for a variable float* pf
, you have (int) *pf == *((int*) pf)
. Sort of like commutativity in mathematics...
However this does not seem to be the case. I wrote a test program:
#include <stdio.h>
int main(int argc, char *argv[]){
float f = 3.3;
float* pf = &f;
int i1 = (int) (*pf);
int i2 = *((int*) pf);
printf("1: %d, 2: %d
", i1, i2);
return 0;
}
and on my system the output is
1: 3, 2: 1079194419
So casting the pointer seems to work differently from casting the value.
Why is that? Why does the second version not do what I think it should?
And is this platform-dependent, or am I somehow invoking undefined behaviour?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…