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?
CodePudding user response:
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
