简体   繁体   English

在取消引用 void 指针后强制转换为 int 是否正确?

[英]It is correct to cast to int after dereferencing a void pointer?

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 ) 学习 C 编程;Jeff Szuhay

'with casting, we can now go [...]' '通过铸造,我们现在可以 go [...]'

The question is - can we really?问题是——我们真的可以吗?

Dereferencing and Casting Void Ptr (Learn C Programming, Jeff Szuhay)取消引用和铸造 Void Ptr(学习 C 编程,Jeff Szuhay)

'with casting, we can now go [...]' '通过铸造,我们现在可以 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 .好吧,它尝试取消引用void*并将结果转换为int That's not how it should be done.这不是应该做的。 You must first cast to int* and then dereference that int* .您必须首先转换为int*然后取消引用该int*

int h = *(int*)aPtr;    // now dereferenced ok (assuming `height` is an `int`)
//      ^   ^
//      |   |
//      |  proper cast
//      |
// dereferencing the right thing

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM