Void Pointer in C
A void pointer (or generic pointer) in C is a special type of pointer that can point to any data type. It is used when you want to store the address of any data type, but you don’t know the data type beforehand. Since a void pointer does not have a specific type, it cannot be dereferenced directly.
Definition
A void pointer is a pointer that can point to any data type. It is declared using the void*
keyword. However, you cannot directly dereference a void pointer without first casting it to another pointer type.
The syntax for declaring a void pointer is:
Syntax:
void *pointer_name;
Example: Void Pointer
This example demonstrates how to use a void pointer to store the address of different data types, and how to dereference it after casting to the appropriate type.
Example Code:
#include <stdio.h>
int main()
{
int num = 10;
float pi = 3.14;
char letter = 'A';
void *ptr; // Declare a void pointer
ptr = # // Pointing to an integer
printf("Value of num: %d\n", *(int*)ptr); // Casting void pointer to int pointer
ptr = π // Pointing to a float
printf("Value of pi: %.2f\n", *(float*)ptr); // Casting void pointer to float pointer
ptr = &letter; // Pointing to a character
printf("Value of letter: %c\n", *(char*)ptr); // Casting void pointer to char pointer
return 0;
}
Output
Value of num: 10
Value of pi: 3.14
Value of letter: A
Value of pi: 3.14
Value of letter: A
Key Points
- A void pointer can point to any data type, but it cannot be dereferenced directly.
- To dereference a void pointer, you must first cast it to the appropriate pointer type.
- Void pointers are particularly useful in situations where the data type is not known in advance (e.g., in functions that can accept different data types).
- Although a void pointer can point to any type of data, it cannot be directly involved in arithmetic operations unless it is cast to a specific type first.