Course contentsShow
← C
Lesson 509 of 1,2197. PointersFree lesson

Casting `void *` to specific types

Casting void * to specific types

What you'll learn: How to tell the compiler which data type a generic void pointer is actually pointing to so you can retrieve its value.

The Mystery Box

In C, a void * is like a mysterious shipping crate. You know it contains something, and you know exactly where it is in the warehouse (memory), but the label has been ripped off. Because the compiler doesn't know if the crate contains a delicate vase (an int) or a heavy anvil (a double), it won't let you open it.

If you try to "dereference" (peek inside) a void * directly, the compiler will throw an error. To get the data out, you must perform a cast. Casting is your way of telling the compiler: "Trust me, I know what's in here. Treat this memory address as a specific type."

The Casting Syntax

To use the data, you first convert the void * back into a typed pointer by placing the desired type in parentheses, like (int *). Once it has a type, you can use the asterisk * to look at the value inside.

#include <stdio.h>

int main() {
    int secretValue = 42;
    void *genericPtr = &secretValue; // The crate is sealed

    // We can't do: int x = *genericPtr; // Error!

    // Step 1: Tell the compiler it's an int pointer: (int *)genericPtr
    // Step 2: Access the value with a leading *: *(int *)genericPtr
    int discoveredValue = *(int *)genericPtr;

    printf("The mystery box contained: %d\n", discoveredValue);
    
    return 0;
}

Why this matters

You might wonder why we don't just use int * from the start. The power of casting void * appears when writing "generic" logic. Imagine a function that saves data to a file. By using void *, that single function can accept an int, a float, or a custom struct. Inside the function, you simply cast the pointer to the type you need to process, allowing one piece of code to handle many different types of data.

Just be careful: if you tell the compiler a crate contains a vase but it actually contains an anvil, your program will likely crash or produce "garbage" data. The compiler trusts your cast completely.

Key takeaway

A void * must be cast to a specific pointer type (like int *) before you can access the data it points to.