Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use a void pointer?

Tags:

c++

c

pointers

I understand the use of void pointer for malloc implementation.

void* malloc  ( size_t size ); 

Can anyone suggest other reasons or provide some scenarios where it is useful in practice.

Thanks

like image 437
Mac13 Avatar asked Jun 22 '09 05:06

Mac13


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. A void pointer can be a null pointer.

What is the limitation of void pointer?

The only limitations with void pointers are: you cannot dereference void pointer for obvious reasons. sizeof(void) is illegal. you cannot perform pointer arithmetics on void pointers.

What is the difference between void and void pointer?

Void refers to the type. Basically, the type of data that it points to can be any. If we assign the address char data type to a void pointer, it will become a char Pointer, if int data type, then int pointer, and so on. Any pointer type is convertible to a void pointer.

What is the use of void in C?

The literal meaning of void is empty or blank. In C, void can be used as a data type that represents no data.


1 Answers

One good scenario void* use is when you want to implement any generic ADT's, in case you just don't know what datatype it going to keep and deal with. For example, a linked list like the following:

typedef struct node_t node; struct {     void* data;     node* prev, next; } node_t;  typedef struct list_t list; typedef void* (func)(void*) cpy_func; typedef void (func)(void*) del_func; struct {    node* head, tail, curr;    cpy_func copy;    del_func delete; } list_t;  initializeLinkedList(cpy_func cpy, del_func del); //here you keep going defining an API 

Here for example you will pass in initialization function pointers to other functions which will be capable of copying your datatype to your list and freeing it afterwards. So by using void* you make your list more generic.

I think void* remained in C++ only because of backward compatibility, since in C++ you have more safe and sophisticated ways to achieve the same result like templates, functors, etc., and you don't need to use malloc while programming C++.

Regarding C++, I don't have any specific useful examples.

like image 143
Artem Barger Avatar answered Oct 03 '22 00:10

Artem Barger