什么时候在C中需要void指针? [英] When is casting void pointer needed in C?

查看:121
本文介绍了什么时候在C中需要void指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在看Mitchell,Oldham和Samuel撰写的 Advanced Linux Programming 。我已经在pthreads部分中看到了一些有关void指针和强制转换的东西,这使我感到困惑。

I've been looking at Advanced Linux Programming by Mitchell, Oldham and Samuel. I've seen in the section on pthreads something about void pointers and casting that confuses me.

将参数传递给pthread_create()时,它们不会将指针强制转换为一个空指针,即使那是函数所期望的。

Passing an argument to pthread_create(), they don't cast the pointer to a void pointer even though that is what the function expects.

pthread_create( &thread, NULL, &compute_prime, &which_prime );

此处, which_prime 类型为 int

但是使用pthread_join从线程返回一个值,他们确实将变量强制转换为void指针。

But taking a value returned from the thread using pthread_join, they DO cast the variable to void pointer.

pthread_join( thread, (void*) &prime );

此处, prime 类型为 int

为什么要在第二个实例而不是在第一个实例中进行转换?

Why is casting done in the second instance and not in the first?

推荐答案

第二个示例很好地说明了为什么强制转换为 void * 通常是一个错误。

The second example is a good example of why casting to void* is usually a mistake. It should be

void *primep = ′  // no cast needed
pthread_join(thread, &primep);

因为 pthread_join 需要 void ** 作为第二个参数。 void * 仅确保错误通过编译器,因为 void * 会转换为无效**

because pthread_join takes a void** as its second argument. The void* only makes sure the bug passes the compiler because the void* is converted to void** automatically.

因此,当时,您需要转换为 void * 或后退:

So, when do you need to cast to void* or back:


  • 当使用存储为整数的指针时((u) intptr_t );

  • 将指针传递给具有不完整原型的函数并采用 void * 时(或使用不同类型的指针,您有 void * );这通常意味着函数采用可变数量的参数,例如 printf

  • when working with pointers stored as integers ((u)intptr_t);
  • when passing pointers to functions that have an incomplete prototype and take void* (or take a different type of pointer and you have void*); that usually means functions taking a variable number of arguments such as printf.

这篇关于什么时候在C中需要void指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆