C++ Pointers: Void Pointer
Syntax
void *pointer_name;
Example
#include<iostream>
using namespace std;
int main()
{
int num = 10;
float decimal = 2.3;
char letter = 'a';
void *ptr;
ptr = #
cout << "Integer value is: " << *((int*)ptr) << endl;
ptr = &decimal;
cout << "Decimal value is: " << *((float*)ptr) << endl;
ptr = &letter;
cout << "Character value is: " << *((char*)ptr) << endl;
return 0;
}
Output
Integer value is: 10
Decimal value is: 2.3
Character value is: a
Explanation
A void pointer is a pointer that has no associated data type with it. A void pointer can hold address of any type and can be typecasted to any type.
In the above example, we have created a void pointer ptr
which can hold the address of any type. We have assigned the address of num
to ptr
and then typecasted it to an integer pointer to print the value of num
. Similarly, we have assigned the addresses of decimal
and letter
to ptr
and typecasted it to their respective data types to print their values.
Use
- Void pointers are used when the data type of the pointer is uncertain or varies.
- Void pointers are used with malloc() function to allocate memory dynamically.
Important Points
- Using void pointers reduces the efficiency of the program as the typecasting and dereferencing take time.
- As void pointers have no associated data type, they cannot be dereferenced directly.
- Always typecast the void pointer to the correct pointer type before dereferencing.
Summary
- Void pointers are pointers that have no associated data type.
- Void pointers can be used to hold address of any data type and can be typecasted to any data type.
- Void pointers are used when the data type of the pointer is uncertain or varies.
- Always typecast the void pointer to the correct pointer type before dereferencing.