void pointer in C++ with example

void pointer is used to store the address of a variable of a different data type.

Let us understand this in detail,

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

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

Because both x and ptr are int type variables, ie both have the same data type.

In other words, we cannot store the address of int variable in float or other data-type variable, such as-

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

Because here *ptr is float type variable while x is an int type variable.

But using void pointer we can store the address of different data -type address in the different type of data-type (void).

declaration of void pointer

The syntax of void pointer declaration is given below-

void *variable-name:

void pointer is useful, you can understand in this way, as we have declared 3 different types of variables-

int x;
float y;
char z;

So without a void pointer, to store the address of these 3 variables, we have to declare the 3 pointer type variable of the same data type separately –

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

Then, the address will be store like this-

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

Using void pointer, we can declare the address of 3 different variables only single void type pointer -variable –

int x;
float y;
char z;
void *ptr

Now, we can store the address of int x, float y and char z (different types of variables) in a pointer-variable * ptr-

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 does not belong to any data-type, so here we make an implicit call to access the address –

*(data-type *) pointer-variable;

An example of this is given below –

void pointer program in C++

#include<iostream.h>
using namespace std;
int main()
{
   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;

return 0;
}

OUTPUT

x: 3 0x8f41fff4
y: 1.2  0x8f41fff0
z: c  0x8f41ffef

more about pointer


Previous- Pointer in C++
Next- memory allocation in C++


Like it?

Leave a Reply

Your email address will not be published.