Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

casting - In C, if I cast & dereference a pointer, does it matter which one I do first?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following says get the float at pf and convert it to an integer. The casting here is a request to convert the float into an integer. The compiler produces code to convert the float value to an integer value. (Converting float values to integers is a "normal" thing to do.)

int i1 = (int) (*pf);

The following says first FORCE the compiler to think pf points to an integer (and ignore the fact that pf is a pointer to a float) and then get the integer value (but it isn't an integer value). This is an odd and dangerous thing to do. The casting in this case DISABLES the proper conversion. The compiler performs a simple copy of the bits at the memory (producing trash). (And there could be memory alignment issues too!)

int i2 = *((int*) pf);

In the second statement, you are not "converting" pointers. You are telling the compiler what the memory points to (which, in this example, is wrong).

These two statements are doing very different things!

Keep in mind that c some times uses the same syntax to describe different operations.

=============

Note that double is the default floating point type in C (the math library typically uses double arguments).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...