void pointer

void pointer used to store the different data-type of address in one single void type variable. see diagram below,

void-pointer

let’s explore it,

As we know, a pointer variable can store the address of same type of variable, i.e. the int type pointer variable will only store the addresses of int type variables,

 int x = 6;
 int *ptr;
 ptr = &x;  // right

because x and ptr, both are int type variable.

In other words, we can not store the address of variable type float or char in int types of variables, such as-

int x = 6;
float *ptr;
ptr = &x; // wrong

because *ptr is float type variable while x is int type variable.

But in C++ we can store the address of different type variables (int, float) in a single variable, using a void type of data type.

The syntax for declaring a void pointer is given below.

SYNTEX:-

void *variable:

void pointer is useful, you can understand it as, if we have declared 3 different type of variables,

int x;
float y;
char z;

so, store the address of these three variable, we have to declare 3 pointer type variable of same data type.
such as,

int *ptr1;
float *ptr2;
char *ptr3;

then,address will store as follows-

ptr1=&x; // for int data type
ptr2=&y; // for float data type
ptr3=&z; // for char data type

while, using void data type, first variable declare, same as above-

int x;
float y;
char z;

then, we declare a void type pointer

void *ptr;

now, we can access int x, float y and char z (different type of variable) address using one pointer-variable *ptr  one by one, as follows-

ptr = &x; // for int data type
cout<<ptr

ptr = &y; // for float data type
cout<<ptr;

ptr = &z; // for char data type
cout<<ptr;

Because that void is not related to any one of the data types, so here we do an emplicit call to print the store value in address.

see below

*(data-type *) pointer-variable;

Let’s try with an example-

#include<iostream.h>
#include<conio.h>

void main()
{
   clrscr();

    int x=3;
   float y=1.2;
   char z='c';

   void *ptr; //void pointer declaration

// for int type variable
   ptr = &x;
   cout<<"x: "<<*(int *)ptr<<"  "<<ptr;

   cout<<endl;

 //for float type variable
   ptr = &y;
   cout<<"y: "<<*(float *)ptr<<"  "<<ptr;

   cout<<endl;

   //for char type variable
   ptr = &z;
   cout<<"z: "<<*(char *)ptr<<"  "<<ptr;
   cout<<endl;

   getch();
}
OUTPUT:-
x: 3 0x8f41fff4
y: 1.2  0x8f41fff0
z: c  0x8f41ffef

more about pointer


previous-Pointer in C++

next-Memory Management and Types