Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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. Why is this useful? Why not directly create desired type of pointer instead of a void?

like image 608
Ann Avatar asked Jun 07 '13 14:06

Ann


People also ask

Do I need to cast a 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. A null pointer is a pointer that does not point to an address.

What is the purpose of a void pointer?

The void pointer in C is a pointer that is not associated with any data types. It points to some data location in the storage. This means that it points to the address of variables. It is also called the general purpose pointer.

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.

What happens when you typecast a pointer?

An open (void) pointer can hold a pointer of any type. Casting an open pointer to other pointer types and casting other pointer types to an open pointer does not result in a compile time error. Note: You might receive a runtime exception if the pointer contains a value unsuitable for the context.


1 Answers

There are two reasons for casting a void pointer to another type in C.

  1. If you want to access something being pointed to by the pointer ( *(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?

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.

like image 199
wolfgang Avatar answered Sep 22 '22 08:09

wolfgang