为什么类型转换为空指针? [英] Why type cast a void pointer?
问题描述
作为 C 的新手,我从 void 指针中得到的唯一实际用途是用于可以在给定指针中存储不同数据类型的多功能函数.因此,我在进行内存分配时没有对指针进行类型转换.
Being new to C, the only practical usage I have gotten out of void pointers is for versatile functions that may store different data types in a given pointer. Therefore I did not type-cast my pointer when doing memory allocation.
我看过一些代码示例,有时会使用 void 指针,但它们会进行类型转换.为什么这很有用?为什么不直接创建所需类型的指针而不是 void?
I have seen some code examples that sometimes use void pointers, but they get type-cast. Why is this useful? Why not directly create desired type of pointer instead of a void?
推荐答案
在 C 中将 void 指针强制转换为另一种类型有两个原因.
There are two reasons for casting a void pointer to another type in C.
- 如果你想访问指针所指向的东西 (
*(int*)p = 42
) - 如果您实际上是在 C 和 C++ 的公共子集中编写代码,而不是真正的"C.另见 我是否转换了 malloc 的结果?
1 的原因应该是显而易见的.第二个是因为 C++ 不允许从 void*
到其他类型的隐式转换,而 C 允许.
The reason for 1 should be obvious. Number two is because C++ disallows the implicit conversion from void*
to other types, while C allows it.
这篇关于为什么类型转换为空指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!