What happens when a pointer is typecasted to a basic data type. Why do we get some value?
For example:
int h=4;
int * ph=&h;
printf("%p",ph);
printf("%d",ph);
Both the print statements print different values...
What happens when a pointer is typecasted to a basic data type. Why do we get some value?
For example:
int h=4;
int * ph=&h;
printf("%p",ph);
printf("%d",ph);
Both the print statements print different values...
printf("%p",ph);
says to the runtime "See over there, that memory is a pointer, load it and print it out as hex please". Note that this is not said to the compiler, the compiler doesnt know what printf is doing (actually most modern compilers sneak a look inside printf statements, you probably got a warning).
printf("%d",ph);
says - "See that piece of memory, its an integer, please load it and print it as a human readable base 10 number"
Given that ph is a pointer to an int the first one does the correct thing, it prints out the value of the pointer.
The second one's behavior depends on the size and representation of int and pointers on your system. The value is 'really' a pointer but you are telling the runtime its an int. ON many many systems pointers and ints are 32 bits. In that case the load will load 32 bits and the print will interpret those bits as an int and print out the base 10 value of the pointer. On other systems pointers might be 64 bits and int would still be 32 bit. Since you dont say what value you get out its hard to know whats going on but if I had to guess I would say that you are getting the same value, one in hex the other in decimal
Note that the second one is whats called 'undefined behavior', you are lying to the system: bad, confusing, unexplained things can happen
This program has undefined behaviour. The type of actual paramater ph (int*
) doesn't match format specifier "%d"
. It can print anything or nothing and simply make your PC explode.