...

/

Examples of Functions Using void*

Examples of Functions Using void*

Learn about multiple functions from the C standard library which rely on void pointers.

Introduction

The C standard library offers us a lot of handy functions with void pointers. Since these functions need to work on any possible data type, they can’t be limited to int or char. They need to accept or return any data type, and they use void* to accomplish this.

We’ll look at a few examples of such functions. We already saw most of them, but we didn’t know they used void pointers.

malloc and calloc

The prototypes are as follows:

void* malloc(size_t size)
void* calloc (size_t num, size_t size);

Since malloc and calloc can allocate a block of any data type, by specifying the size, they must return void*. We then implicitly cast the returned pointer to our desired data type when writing constructs like the following:

int* intPtr = malloc(sizeof(int));

Sometimes it may be a good idea to explicitly cast the return ...