#include <stdio.h>
int main(void)
{
int x = 1000;
char *ptr = &x;
printf("%d\n",*ptr);
return 0;
}
Output: -24 /*In gcc 4.4.3 in Ubuntu 10.04 OS*/
With a warning: initialization from incompatible pointer type
What I think if the base type of the pointer were of int type then it would have retrieved 4 bytes from the location it’s pointing.Then the O/P would have been 1000.But as I changed the base type to char then it would retrieve 1 byte from location it’s pointing when I dereference it.But how the answer is -24.
Again when I changed the program as below
#include <stdio.h>
int main(void)
{
int x = 1000;
float *ptr = &x;
printf("%f\n",*ptr);
return 0;
}
The output becomes 0.000000 with same warning.when I derefence the pointer it would retrieve 4 bytes from the location it’s pointing.But how the O/P is 0.000000.I’m bit confused.Can u guys plz explain it.I new in C programming, so any mistake in asking the question, plz forgive me. Thanx
Dereferencing a character pointer got you the first character-sized chunk of the internal representation of 1000 as an integer. That character was then promoted to a
int(as per the rules for varidac arguments), and interpreted as integer.On you machine, with that compiler, the result was -24.
Character sized chunk was probably a 8-bit byte.
The integer was probably represented by 4 or 8 of those bytes.
The internal representation was probably 2s-complement, and was probably stored in little endian order.
Do you begin to see why the result wasn’t easy for you to predict?
Doing the same thing with a float pointer returned a
floatsized chuck of memory instead of achar, and now you may have real (heh!) trouble because we don’t know, at this point if thefloatrepresentation will even fit in aintrepresentation, so you may be accessing uninitialized memory.In any case, when you dereferenced the
float*it interpreted that memory asfloat(which has a rather more complex internal structure than a character or even a 2s-complement integer), and promoted it to adouble(those rules for varidac arguments again) then an attempt was made interpret that representation as an integer (and if thefloatdid fit in anint, thedoubleprobably doesn’t, so you’re interpreting part of the double as an int!). Ugh.This situation is even worse than the last because it involves the IEEE floating point representation standards and two chances to have the sizes not match up at all.
So the lesson here is:
Don’t do that.
And the subsidiary lesson, only for experts is
Still don’t do it.
because if you want to perform all these silly reinterpretations you want to have exact and explicit control of them.