简体   繁体   English

为什么要输入一个void指针?

[英]Why type cast a void pointer?

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. 作为C的新手,我从void指针中获得的唯一实际用法是用于在给定指针中存储不同数据类型的通用函数。 Therefore I did not type-cast my pointer when doing memory allocation. 因此,在进行内存分配时,我没有输入指针。

I have seen some code examples that sometimes use void pointers, but they get type-cast. 我见过一些有时使用void指针的代码示例,但是它们是类型转换的。 Why is this useful? 为什么这有用? Why not directly create desired type of pointer instead of a void? 为什么不直接创建所需类型的指针而不是void?

There are two reasons for casting a void pointer to another type in C. 在C中将void指针转换为另一个类型有两个原因。

  1. If you want to access something being pointed to by the pointer ( *(int*)p = 42 ) 如果要访问指针指向的内容( *(int*)p = 42
  2. 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? 如果你实际上是在C和C ++的公共子集中编写代码,而不是“真正的”C.参见我是否转换了malloc的结果?

The reason for 1 should be obvious. 1的原因应该是显而易见的。 Number two is because C++ disallows the implicit conversion from void* to other types, while C allows it. 第二个是因为C ++不允许从void*到其他类型的隐式转换,而C允许它。

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 */
}

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

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