0
0
CConceptBeginner · 3 min read

What is Void Pointer in C: Simple Explanation and Example

A void pointer in C is a special type of pointer that can hold the address of any data type but does not have a type itself. It is used when you want a generic pointer that can point to different types of data, but you must cast it to the correct type before using it.
⚙️

How It Works

Think of a void pointer as a universal remote control that can connect to any device, but it doesn't know what buttons to press until you tell it the device type. In C, a void pointer stores the address of some data, but it does not know the data's type or size. This means you cannot directly use the data it points to without first telling the compiler what type it is.

Because the void pointer has no type, it cannot be dereferenced directly. You must convert (cast) it to a pointer of a specific type before accessing the data. This makes void pointers very flexible for writing functions or data structures that work with different data types.

💻

Example

This example shows how a void pointer can point to an integer and a float by casting it to the correct type before use.

c
#include <stdio.h>

int main() {
    int num = 10;
    float pi = 3.14f;
    void *ptr;  // void pointer

    ptr = &num;  // point to int
    printf("Integer value: %d\n", *(int *)ptr);  // cast to int pointer before dereference

    ptr = &pi;   // point to float
    printf("Float value: %.2f\n", *(float *)ptr);  // cast to float pointer before dereference

    return 0;
}
Output
Integer value: 10 Float value: 3.14
🎯

When to Use

Use a void pointer when you want to write flexible code that can handle different data types without repeating similar code for each type. For example:

  • Generic functions like memory copy or comparison that work with any data type.
  • Data structures like linked lists or trees that store different types of data.
  • Interfacing with low-level APIs or libraries where the data type is not fixed.

Remember, you must always cast the void pointer back to the correct type before using it to avoid errors.

Key Points

  • A void pointer can hold the address of any data type.
  • It cannot be dereferenced directly without casting.
  • Useful for writing generic and reusable code.
  • Always cast to the correct type before accessing the data.

Key Takeaways

A void pointer is a generic pointer that can point to any data type in C.
You must cast a void pointer to the correct type before dereferencing it.
Void pointers enable writing flexible and reusable code for multiple data types.
They are commonly used in generic functions and data structures.
Always ensure the correct type is used to avoid runtime errors.