What is Void Pointer in C: Simple Explanation and Example
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.
#include <stdio.h> int main() { int num = 10; float pi = 3.14f; void *ptr; // void pointer ptr = # // point to int printf("Integer value: %d\n", *(int *)ptr); // cast to int pointer before dereference ptr = π // point to float printf("Float value: %.2f\n", *(float *)ptr); // cast to float pointer before dereference return 0; }
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.