C语言 为什么类型转换为空指针?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16986214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why type cast a void pointer?
提问by Ann
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.
作为 C 的新手,我从 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?
我看过一些代码示例,有时会使用 void 指针,但它们会进行类型转换。为什么这很有用?为什么不直接创建所需类型的指针而不是 void?
回答by wolfgang
There are two reasons for casting a void pointer to another type in C.
在 C 中将 void 指针转换为另一种类型有两个原因。
- If you want to access something being pointed to by the pointer (
*(int*)p = 42) - If you are actually writing code in the common subset of C and C++, rather than "real" C. See also Do I cast the result of malloc?
- 如果要访问指针 (
*(int*)p = 42)指向的内容 - 如果您实际上是在 C 和 C++ 的公共子集中编写代码,而不是“真正的”C。另请参阅我是否转换了 malloc 的结果?
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.
1 的原因应该是显而易见的。第二个是因为 C++ 不允许从void*到其他类型的隐式转换,而 C 允许它。
回答by Guillaume
You need to cast void pointers to something else if you want to dereference them, for instance you get a void pointer as a function parameter and you know for sure this is an integer:
如果您想取消引用它们,您需要将 void 指针转换为其他内容,例如,您获得一个 void 指针作为函数参数,并且您确定这是一个整数:
void some_function(void * some_param) {
int some_value = *some_param; /* won't work, you can't dereference a void pointer */
}
void some_function(void * some_param) {
int some_value = *((int *) some_param); /* ok */
}

