void* aPtr = NULL; // we don't yet know what it points to.
...
aPtr = &height; // it has the address of height, but no type yet.
...
int h = (int)*aPtr; // with casting, we can now go to that address
// and fetch an integer value.
( Learn C Programming; Jeff Szuhay )
'with casting, we can now go [...]'
The question is - can we really?
Dereferencing and Casting Void Ptr (Learn C Programming, Jeff Szuhay)
'with casting, we can now go [...]'
The question is - can we really?
Yes, but the shown code doesn't do any dereferencing. Well, it tries to dereference a void*
and cast the result to int
. That's not how it should be done. You must first cast to int*
and then dereference that int*
.
int h = *(int*)aPtr; // now dereferenced ok (assuming `height` is an `int`)
// ^ ^
// | |
// | proper cast
// |
// dereferencing the right thing
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.