Implicit conversion to void *
What you'll learn: How C allows you to pass any data pointer into a "generic" pointer without needing messy type casting.
The Universal Adapter
In previous lessons, we learned that C is usually very strict about types. If a function expects an int *, you cannot hand it a char * without the compiler complaining. However, the void * (void pointer) is the special exception to this rule.
Think of a void * as a universal power adapter. In C, any data pointer—whether it points to an integer, a float, or a complex custom structure—can be automatically "plugged into" a void * variable. You don't have to tell the compiler "treat this integer pointer as a void pointer"; the compiler simply accepts it. This is called implicit conversion.
Why this is useful
Imagine you are writing a function that saves data to a file. You don't want to write one function for saveInt(), another for saveFloat(), and another for saveStudent(). Instead, you want one saveData() function that accepts a pointer to anything.
Because of implicit conversion, you can pass any specific pointer type into a function parameter defined as void *. C assumes you know what you’re doing and handles the transition behind the scenes.
Seeing it in action
In the example below, notice that we don't need to use parentheses to cast our pointers when calling the displayAddress function.
#include <stdio.h>
// This function accepts a "pointer to anything"
void displayAddress(void *ptr) {
printf("The data is stored at memory address: %p\n", ptr);
}
int main() {
int age = 25;
double price = 19.99;
char grade = 'A';
// We pass int*, double*, and char* directly.
// The compiler implicitly converts them all to void* for us.
displayAddress(&age);
displayAddress(&price);
displayAddress(&grade);
return 0;
}
The "One-Way" Rule
While you can freely assign a specific pointer (like int *) to a void *, the reverse requires more caution. More importantly, remember that once a pointer is a void *, the compiler forgets what the data is. A void * knows where the data is, but not what it is. You can pass it around easily, but you cannot look at the value it points to (dereference it) until you tell the compiler the original type again.
Key takeaway
Any specific data pointer can be assigned to a void * automatically, making it the perfect tool for writing flexible, generic code.