C++ Void Pointer
A void pointer is a general purpose pointer that can have an address of any data type but is not related to any data type.
Void Pointer Syntax:
void *ptr;
We can't assign a variable's address to a variable of a different data type in C++.To better understand this let see an example below:
int *ptr; //declaration of an integer pointer ptr
float i=14.6; // initialization of a floating variable i
ptr= &i; // This statement throws an error.
Explanation:
We define a pointer of type integer, ptr, and a float variable, 'i', in the preceding example. We try to save the address of 'i' variable in 'ptr' after declaration, but this is not feasible in C++ since the variable cannot carry the addresses of various data types.
Another example of a program containing void pointer in C++:
#include <iostream>
#inlcude <bits/stdc++.h>
using namespace std;
int main()
{
int *ptr;
float i= 14.6;
ptr = &i; // error
std::cout << "The value of *ptr is : " <<*ptr<< std::endl;
return 0;
}
OUTPUT:
error: cannot convert ‘float*’ to ‘int*’ in assignment
ptr = &f; //error
Explanation:
In the above program, we define an integer pointer and a float variable. An integer pointer variable cannot point to a float variable, but it can only point to an integer variable. The above problem was solved in C++ by utilizing the void pointer, which may contain the address of any data type.
Another example of a program containing void pointer in C++:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
void *ptr; // declaration of a void pointer
int i=19; // initialization of an integer variable
ptr=&i; // storing the address of 'i' variable in a void pointer variable ptr.
std::cout << &i << std::endl;
std::cout << ptr << std::endl;
return 0;
}
OUTPUT:
0x61ff08
0x61ff08
press any key to continue……
Explanation:
We declare void pointer variable and integer variable in the preceding program, which contains the address of void pointer integer variable.
Advantages of Void Pointer in C++
- Because malloc() and calloc() return the void * type, they may be used to allocate memory of any data type (due to the void *).
- Normal functions in C are executed using void pointers. For example, in qsort, the compare function is used ().
Important fact: It is not possible to ignore void pointers. The following program, for example, does not compile.
#include<stdio.h>
#include<iostream>
#include<bits/stdc++.h>
int main()
{ int i = 10;
void *ptr = &i;
printf("%d", *ptr);
return 0;
}
OUTPUT:
Compiler error: 'void*' is not a pointer-to-object type
Following program run fine with the compiler:
#include<stdio.h>
#include<iostream>
#include<bits/stdc++.h>
int main()
{int i = 20;
void *ptr = &i;
printf("%d", *(int *)ptr);
return 0;
}
OUTPUT:
20