void Pointers Definition

Learn about void pointers, a key concept for implementing genericity in C.

Introduction

Up until this point, we’ve worked with various pointer types, such as:

  • Pointers to int
  • Pointers to float
  • Pointers to char
  • Pointers to custom data types, defined using structures

One limiting factor was that different pointer types are not often compatible. For example, an int pointer can’t usually point to a floating point number. This fact introduces an interesting problem. The problem is what happens when we want to write a function that doesn’t depend on the data type, as the processing is identical. We’d have to create multiple almost identical functions, where the only difference is the data type of the arguments.

For example, let’s look at the memcpy function. Its purpose is to copy data from one memory block to another memory block. We shouldn’t care what that data is. We just need to copy it byte by byte. How would we go about implementing it? Should we create a memcpy_int, memcpy_float, and so on for every data type we need to copy?

The answer is no! It wouldn’t be a good code design. Not only do we need to create a potentially unlimited number of identical functions, but we also have to remember to use the correct one for the current data type.

The solution is to use void pointers.

The void pointers

A void pointer (void*) is a pointer that can point to any other pointer. It doesn’t have a concrete data type (like an int pointer that points to an int). We can view it as a placeholder or wildcard pointer. It simply accepts any other pointer.

Consider the following code, where we create a void pointer at in line 11. We initialize it using an int pointer and a float pointer. The code compiles fine, proving that void* can point to any T*, where T is a data type (like int, float).

Get hands-on with 1400+ tech skills courses.