Void Pointers or Generic Pointers

The void pointer, also known as the generic pointer, is a special type of pointer that can be pointed at objects of any data type. Literal meaning of generic pointer is a pointer which can point any type of data. A void pointer is declared like a normal pointer, using the void keyword as the pointer's type:
void *ptr;
Here ptr is generic pointer. There are some points which should be kept in mind while deal with generic pointer and these are list below:

1. Generic Pointers cannot be dereference

#include<iostream>
using namespace std;
int main()
{
int x=10;
void *ptr;
ptr = &x;
cout<< *ptr;
return 0;
}

The above program output is tested on www.jdoodle.com

Output:

jdoodle.cpp: In function 'int main()':
jdoodle.cpp:8:9: error: 'void*' is not a pointer-to-object type
 cout<< *ptr;
         ^
          or 
compile time error


2. sizeof() operator can be used to check size of Generic Pointers 

#include<iostream>
using namespace std;
int main()
{
int x=10;
void *ptr;
ptr = &x;
cout<< sizeof(ptr);
return 0;
}

The above program output is tested on www.jdoodle.com

Output:  8

3. Generic pointer can hold any type of pointers like char, struct pointer etc without ant typecasting

#include<iostream>
using namespace std;
int main()
{
char ch = 'x';
int i = 2;
void *ptr1;
char *ptr2 = &ch;
int *ptr3 = &i;
ptr1 = ptr2;
cout<< *(char *)ptr2;
cout<<endl;
ptr1 = ptr3;
cout<<*(int *)ptr1;
cout<<endl;
return 0;
}

The above program output is tested on www.jdoodle.com

Output:  
2


Further in Generic pointer are used when we want to return such pointer which is applicable to all types of pointers.

Thanks 
Mukesh Rajput

Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: