The void * generic type
What you'll learn: How to use the void * pointer as a "universal adapter" to point to any data type in C.
The Universal Adapter
In C, pointers are usually picky. An int * wants to point to an integer, and a char * wants to point to a character. If you try to mix them, the compiler will complain. However, there are times when you need a pointer to be flexible—for example, if you are writing a function that needs to handle many different types of data.
This is where the void * (void pointer) comes in. Think of it as a universal adapter. Just as a USB-C port doesn't care if you plug in a phone, a keyboard, or a lamp, a void * can hold the memory address of any data type without causing an error.
The Catch: No Peeking!
While a void * is great for storage, it has a major limitation: the computer no longer knows what is inside that memory address. If you have a void *, you cannot "dereference" it (look at the value) or perform math on it immediately.
Before you can use the data, you must cast it back to its original type. It is like receiving a mystery box; you can carry it around easily, but to see what’s inside, you have to tell the computer exactly what kind of item you are expecting to find.
Example: One Pointer, Many Faces
In the code below, notice how we use a single void * variable to point to two completely different types of data.
#include <stdio.h>
int main() {
int age = 25;
double price = 19.99;
// The generic pointer
void *genericPtr;
// Point to an integer
genericPtr = &age;
printf("Age: %d\n", *(int *)genericPtr); // Cast to int* then dereference
// Point to a double
genericPtr = &price;
printf("Price: %.2f\n", *(double *)genericPtr); // Cast to double* then dereference
return 0;
}
In this example, genericPtr is a chameleon. By using (int *) or (double *), we tell C, "Trust me, for this moment, treat this generic address as this specific type." This flexibility is the foundation for advanced C features like generic lists and sorting functions.
Key takeaway
A void * is a generic pointer that can hold any address, but it must be cast back to a specific type before you can access the data it points to.