Why you can't dereference void *
What you'll learn: You will understand why the compiler prevents you from accessing the data at a void * address without a specific type cast.
The Blind Map
Imagine you are a delivery driver. Someone gives you a GPS coordinate (a pointer) to a package. You arrive at the location, but there’s a catch: the instructions don't tell you if the package is a tiny USB drive, a heavy washing machine, or a pile of loose sand.
Without knowing what is at the address, you don't know how to pick it up. Do you use two fingers? A forklift? A shovel?
In C, a void * is that GPS coordinate. It is a "generic" pointer that can hold the address of any data type. However, because it lacks a type, the compiler is "blind" to the data sitting at that memory address.
The Compiler's Dilemma
Dereferencing a pointer means asking the CPU to "go to this address and read the value." To do this, the compiler needs two crucial pieces of information:
- Size: How many bytes should I read? (4 bytes for an
int? 8 for adouble?) - Interpretation: How should I treat those bits? (As a whole number? A decimal? A character?)
A void * provides neither. If you try to use the * operator on a void *, the compiler will throw an error because it doesn't know where the data ends or how to translate the binary 1s and 0s.
Seeing Through the Void
To access the data, you must "cast" the pointer. This is like telling the delivery driver, "Treat the item at this coordinate as a washing machine."
#include <stdio.h>
int main() {
int secret_number = 42;
void *generic_ptr = &secret_number;
// ERROR: The compiler doesn't know how many bytes to read.
// printf("%d", *generic_ptr);
// SUCCESS: We tell the compiler to treat the address as an int pointer.
int *int_ptr = (int *)generic_ptr;
printf("The value is: %d", *int_ptr);
return 0;
}
By casting to int *, you give the compiler the "vision" it needs to safely step into that memory and retrieve the value.
Key takeaway
You cannot dereference a void * because the compiler doesn't know the size or format of the data it points to; you must first cast it to a specific type.