float f_var = 1.5F;
long *l_ptr = (long *)&f_var;
What is the difference between above statement and below statement?
double *d_ptr = (double *)l_ptr;
My doubt is what makes the difference using "&" in the above statement .
Can you give little example to solve my doubt?
CodePudding user response:
This long *l_ptr = (long *)&f_var;
takes the address of a float
variable and uses it as a pointer to an integer variable. This will result in extremely weird integer values being read if that pointer is dereferenced.
This double *d_ptr = (double *)l_ptr;
uses that pointer to a float
variable (which is seen as a pointer to an integer variable) as a pointer to a double
variable, which among other things is wider than a float
. This, if dereferenced, will result in extremely weird double
values, which include the interpretation of incorrectly accessed memory and all kinds of broken rules.
Do not do either unless you have neglected to mention a lot of in-depth knowledge about neighbouring memory and environment specific type handling.
CodePudding user response:
The &
is the address-of operator. It returns the address of the variable that stores a certain value. Normally, one would do float *f_ptr = &f_var;
to get a float pointer to a value of type float. If you instead use long *l_ptr = (long *)&f_var;
you get a pointer of type long*
pointing to the same variable (which is still a float). This is dangerous and will rarely give the expected result, for two reasons: a) sizeof(long)
might be larger than sizeof(float)
, causing an access to l_ptr
to result in undefined behavior. b) Reading the value with long l = *l_ptr
will be mostly useless, since a float is not a long, and no value conversion took place. The value of l will not be the integer part of the float, as you might expect.
This double *d_ptr = (double *)l_ptr;
has similar problems: While now, both sides are pointers, interpreting a pointer to a long as a pointer to double is only useful in very rare cases (e.g. when working with unions). And double is now for certain longer than float, so doing double d = *d_ptr
will result in undefined behavior.
Bottom line: Neither of these instructions are useful, at least certainly not in beginners code.