A void pointer is a special type of pointer that can point to any data type. This is because a void pointer does not have an associated data type. However, since it doesn’t have a specific type, you cannot dereference it directly without casting it to another pointer type.
Key Concepts
Declaration of a Void Pointer
void* ptr;
This declares a void pointer ‘ptr’ that can hold the address of any data type.
Assigning Addresses to a Void Pointer
int a = 10;
float b = 5.5;
ptr = &a; // Void pointer pointing to an integer
ptr = &b; // Void pointer pointing to a float
Dereferencing a Void Pointer
Since a void pointer does not have a type, you need to cast it to the appropriate type before dereferencing
int* intPtr = (int*)ptr;
cout << *intPtr << endl;
float* floatPtr = (float*)ptr;
cout << *floatPtr << endl;
Example Program: Using Void Pointers
Here’s a complete program that demonstrates the use of void pointers in C++:
#include <iostream>
using namespace std;
void printValue(void* ptr, char type) {
switch (type) {
case ‘i’: // Integer
cout << “Integer: ” << *(int*)ptr << endl;
break;
case ‘f’: // Float
cout << “Float: ” << *(float*)ptr << endl;
break;
case ‘d’: // Double
cout << “Double: ” << *(double*)ptr << endl;
break;
case ‘c’: // Character
cout << “Character: ” << *(char*)ptr << endl;
break;
default:
cout << “Invalid type!” << endl;
}
}
int main() {
int a = 10;
float b = 5.5f;
double c = 3.14159;
char d = ‘A’;
void* ptr; // Declare a void pointer
// Using the void pointer to point to different data types
ptr = &a;
printValue(ptr, ‘i’);
ptr = &b;
printValue(ptr, ‘f’);
ptr = &c;
printValue(ptr, ‘d’);
ptr = &d;
printValue(ptr, ‘c’);
return 0;
}
Explanation of the Program
Function ‘printValue’
This function takes a void pointer and a type identifier. It casts the void pointer to the appropriate type based on the type identifier and prints the value. The switch statement is used to handle different data types.
Main Function
- Four variables of different types (int, float, double, char) are declared.
- A void pointer ‘ptr’ is used to point to each of these variables.
- The ‘printValue’ function is called with the void pointer and a type identifier to print the value pointed to by the void pointer.