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

查看:32
本文介绍了什么时候需要在 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(),它们不会将指针强制转换为 void 指针,即使这是函数所期望的.

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_primeint 类型.

但是使用 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 类型.

Here, prime is of type int again.

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

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_joinvoid** 作为第二个参数.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.

因此,当 do 时,您需要强制转换为 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天全站免登陆