Void Pointers in C

We have learned in chapter Pointer Basics in C that if a pointer is of type pointer to int or (int *) then it can hold the address of the variable of type int only. It would be incorrect, if we assign an address of a float variable to a pointer of type pointer to int. But void pointer is an exception to this rule. A void pointer can point to a variable of any data type. Here is the syntax of void pointer.

Syntax: void *vp;

Let’s take an example:

Here vp is a void pointer, so you can assign the address of any type of variable to it.

A void pointer can point to a variable of any data type and void pointer can be assigned to a pointer of any type.

Dereferencing a void Pointer

We can’t just dereference a void pointer using indirection (*) operator. For example:

It simply doesn’t work that way!. Before you dereference a void pointer it must be typecasted to appropriate pointer type. Let me show you what I mean.

For example: In the above snippet void pointer vp is pointing to the address of integer variable a. So in this case vp is acting as a pointer to int or (int *). Hence the proper typecast in this case is (int*).

Now the type of vptr temporarily changes from void pointer to pointer to int or (int*) , and we already know how to dereference a pointer to int, just precede it with indirection operator (*)

Note: typecasting changes type of vp temporarily until the evaluation of the expression, everywhere else in the program vp is still a void pointer.

The following program demonstrates how to dereference a void pointer.

Expected Output:

Pointer Arithmetic in Void Pointers

Another important point I want to mention is about pointer arithmetic with void pointer. Before you apply pointer arithmetic in void pointers make sure to provide a proper typecast first otherwise you may get unexcepted results.

Consider the following example:

Here we have assigned the name of the array one_d to the void pointer vp. Since the base type of one_d is a pointer to int or (int*), the void pointer vp is acting like a pointer to int or (int*). So the proper typecast is (int*).

The following program demonstrates pointer arithmetic in void pointers.

Expected Output:

The void pointers are used extensively in dynamic memory allocation which we will discuss next.

5 thoughts on “Void Pointers in C

  1. a few typo in snippets under “Pointer Arithmetic in Void pointers”:
    int one_d[5] = {12, 19, 25, 34, 46}, i;
    void *vp = one_d;

    printf(“%d”, arr + 1); // wrong => printf(“%d”, one_d+ 1);

    Same issue, for the next snippet.

  2. can i use an array of void pointer? Can i assign the value of a void pointer at an another void pointer? Thanks

Leave a Comment