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 [...]'
问题是 - 我们真的可以吗?
最佳答案
Dereferencing and Casting Void Ptr (Learn C Programming, Jeff Szuhay)
'with casting, we can now go [...]'
The question is - can we really?
是的,但是显示的代码没有进行任何解除引用。好吧,它尝试取消引用 void*
并将结果转换为 int
。这不是应该做的。您必须先转换为 int*
,然后 取消对 int*
的引用。
int h = *(int*)aPtr; // now dereferenced ok (assuming `height` is an `int`)
// ^ ^
// | |
// | proper cast
// |
// dereferencing the right thing
关于c - 在取消引用 void 指针后转换为 int 是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70719853/