Normally we know that a pointer can hold the address of any location provided the types of both the location and the pointer are same. But there is an exception. There is a general purpose pointer in C++ called void pointer. Void pointer can hold the address of any type of location and it can transfer the address to another pointer of the location type.
Here is an example showing the use of void pointer in C++ programs.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
char ch[100];
char *ptr;
void *p;
cout<< "\nEnter a string:";
cin.get(ch,100);
p=ch;
ptr=(char )p;
cout<< endl<< "Now string display through the 'char' pointer:"<< ptr;
getch();
}
Another example showing the use of void pointer in C++ programs.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num;
int *ptr;
void *p;
cout<< "\nEnter a number:";
cin>>num;
p=#
cout<< endl<< "Address of the variable through void pointer:"<< p;
ptr=(int *)p;
cout<< endl<< "Value display through the 'int' pointer:"<< *ptr;
cout<< endl<< "Address display through the 'int' pointer:"<< ptr;
getch();
}
Through void pointer we can not display the content of a location. Such pointers have some specialized uses C++, such as passing pointers to functions that operate independently of the data type pointed to.
No comments:
Post a Comment