Why does:
const char example;
(uint64*)example
have a value of 140734799798420
and
*(uint64*)example
have a value of 7004431430466964258
p.s. dont worry about the type cast, I am interested why the second *
increases th开发者_JAVA百科e value.
Thanks
Your code gives undefined behaviour. Your second line illegally casts a character to a pointer to a uint64 (most likely an invalid pointer). Your third line attempts to dereference this invalid pointer.
Asking why it does what it does is pointless - it could do different things on different machines and the behaviour could change in the next version of the compiler.
Just don't do it.
As others have said, you've invoked undefined behavior. No particular behavior is guaranteed.
That said, you see different values because you are printing different locations in memory -- the first prints data from the memory location where example
is stored, and the second prints data from the memory location stored as the value of example
.
const char example
Defines a char
variable on the stack without initializing it, so its value will be garbage; probably whatever was last stored in the location on the stack where it was allocated.
(uint64 *)example
Interprets the value of example
as a pointer to (the address of) a uint64
. This prints out the value stored in example
as if it were a pointer.
*(uint64 *)example
Dereferences that pointer. It interprets the value of example
as a pointer to (the address of) a uint64, then prints what is at that address as if it were a uint64.
精彩评论