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

标签 c

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/

相关文章:

c - 如何在字符串中存储ascii值0而不终止它?

c - C语言中匹配IP地址的最佳正则表达式或技术是什么

c - glutSolidSphere 和 GL_LINE_STRIP 在不同位置绘制但基于相同位置

c - 如何退出Contiki代码?

c - 如果我为单个中断创建多个 ISR 会怎样?

c - 1TBS 用于长条件表达式

c - 为什么我自己的 suid-ed 程序仍然保留原来的 uid?

c - 如何用C语言创建特定整数的 block

c - 需要帮助来理解此代码的 Big-O 复杂性的答案

c - C程序中的fork()