Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is casting void pointer needed in C?

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.

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 ); 

Here, which_prime is of type int.

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

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

Here, prime is of type int again.

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

like image 669
Amoeba Avatar asked Dec 09 '13 11:12

Amoeba


People also ask

Do you need to cast void pointer?

A void pointer is a pointer that can point to any type of object, but does not know what type of object it points to. A void pointer must be explicitly cast into another type of pointer to perform indirection.

When would you use a void pointer?

We use the void pointers to overcome the issue of assigning separate values to different data types in a program. The pointer to void can be used in generic functions in C because it is capable of pointing to any data type.

What does casting to void do in C?

Casting to void is used to suppress compiler warnings. The Standard says in §5.2. 9/4 says, Any expression can be explicitly converted to type “cv void.” The expression value is discarded. Follow this answer to receive notifications.

Why is type casting used to access the value of any variable using a void pointer?

Why we use void pointers? We use void pointers because of its reusability. Void pointers can store the object of any type, and we can retrieve the object of any type by using the indirection operator with proper typecasting.


1 Answers

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); 

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.

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

  • 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.
like image 119
Fred Foo Avatar answered Sep 29 '22 06:09

Fred Foo