Information hiding using void pointers
What you'll learn: How to use void * within a structure to hide complex implementation details from the rest of your program.
The Secret Compartment
Imagine you are designing a high-end watch. The user only needs to see the hands and the crown to set the time. They don't need to see the tiny gears, springs, and levers inside. In fact, if they could see and touch those gears, they might accidentally break something.
In C, we use void * (the "generic pointer") to create a "secret compartment" inside a structure. This allows us to store complex data that the rest of the program knows exists but cannot touch or see directly. This is a core pattern for encapsulation, ensuring that the "internals" of a module stay private.
Masking the Details
When we put a void * inside a struct, we are telling the compiler: "This pointer points to something, but I’m not going to tell you what it is yet."
Only the specific functions designed to handle that struct will "cast" that pointer back to its real type to work on it. To everyone else, it’s just a mysterious address.
#include <stdio.h>
#include <stdlib.h>
// The public structure
struct Sensor {
int id;
void *internal_data; // The "secret compartment"
};
// A private structure hidden inside the sensor's implementation file
struct Calibration {
float offset;
float scale_factor;
};
void init_sensor(struct Sensor *s, int id) {
s->id = id;
// We hide the complex Calibration details inside the void pointer
struct Calibration *cal = malloc(sizeof(struct Calibration));
cal->offset = 0.5f;
cal->scale_factor = 1.2f;
s->internal_data = cal;
}
void print_sensor_config(struct Sensor *s) {
// Only this function knows how to "unmask" the data
struct Calibration *cal = (struct Calibration *)s->internal_data;
printf("Sensor %d: Scale is %.1f\n", s->id, cal->scale_factor);
}
int main() {
struct Sensor my_sensor;
init_sensor(&my_sensor, 101);
// The main program can see my_sensor.id, but it has no
// idea what's inside internal_data without a cast.
print_sensor_config(&my_sensor);
free(my_sensor.internal_data);
return 0;
}
Why This Matters
By using this pattern, you protect your code's integrity. If you decide to change the Calibration struct later—perhaps adding a "last_serviced" date—you only have to change the functions that directly handle the sensor. The rest of your program, which just passes the Sensor struct around, doesn't need to change at all. It never saw the gears in the first place!
Key takeaway
Using void * inside a structure allows you to hide implementation details, creating a clean interface that prevents other parts of your program from messing with private data.