C++ Pointer to Void

Before you proceed with this tutorial, be sure to check C++ pointers.

In C++, we cannot assign the address of a variable of one data type to a pointer of another data type. Consider this example:

// pointer is of int type
int *ptr;

// variable is of double type
double d = 9.0;

// Error
// can't assign double* to int*
ptr = &d;

Here, the error occurred because the address is a double type variable. However, the pointer is of int type.

In such situations, we can use the pointer to void (void pointers) in C++. For example,

// void pointer
void *ptr;

double d = 9.0;

// valid code
ptr = &d;

The void pointer is a generic pointer that is used when we don't know the data type of the variable that the pointer points to.


Example 1: C++ Void Pointer

Output

0xffd117ac
0xffd117ac

Here, the pointer ptr is given the value of &f.

The output shows that the void pointer ptr stores the address of a float variable f.


As void is an empty type, void pointers cannot be dereferenced.

void* ptr;
float* fptr;
float f = 2.3;

// assign float address to void pointer
ptr = &f;
cout << *ptr << endl;  // Error

// assign float address to float pointer
fptr = &f;
cout << *fptr << endl;   // Valid

Example 2: Printing the Content of Void Pointer

To print the content of a void pointer, we use the static_cast operator. It converts the pointer from void* type to the respective data type of the address the pointer is storing:

Output

The content of pointer is 2.3

This program prints the value of the address pointed to by the void pointer ptr.

Since we cannot dereference a void pointer, we cannot use *ptr.

However, if we convert the void* pointer type to the float* type, we can use the value pointed to by the void pointer.

In this example, we have used the static_cast operator to convert the data type of the pointer from void* to float*.


C-style casting

We can also use C-style casting to print the value.

// valid
cout << *((float*)ptr);

However, static_cast is preferred to C-style casting.


Note: void pointers cannot be used to store addresses of variables with const or volatile qualifiers.

void *ptr;
const double d = 9.0;

// Error: invalid conversion from const void* to void*
ptr = &d;