When we declare a pointer we specify its type which will be same as the type of the variable whose address the pointer will contain. For example if we will declare an integer pointer then it can contain the address of an integer variable only. Take below example.
1 | int *p,a;
|
2 | char b; |
3 | p=&a; //valid |
4 | p=&b; //invalid, will show an error because p can contain address of integer type variable only |
What if we can have a pointer that can point to any type of variable? This can be done easily using void pointer.
void pointer in C
void pointer is a pointer which is not associated with any data type. It can contain the address of variable of any data type. void pointer is also known as general purpose pointer. We can declare a void pointer in C using void keyword as shown below.1 | void *p; |
2 | int a; |
3 | char b; |
4 | p=&a; //valid |
5 | p=&b; //valid |
The dereference operator or indirection operator (*) is used for dereferencing a pointer. Dereferencing means accessing the value at the address stored in pointer variable. We have to type caste the pointer variable to dereference it because the void pointer is not associated with any data type. The compiler is unable to find the type of variable pointed by the void pointer. This can be done in following way.
1 | void *p; |
2 | int a=20,b; |
3 | p=&a; |
4 | b=*p; //this will show an error |
5 | b=*(( int *)p); //type casting the pointer variable to dereference it |
We can’t perform the pointer arithmetic on void pointer. Take below example.
1 | void *p; |
2 | int a=20; |
3 | p=&a; |
4 | p++; //this will show an error |
Lets make one program to understand the concept of void pointer in C.
01 | #include<stdio.h> |
02 |
03 | void main() |
04 | { |
05 | int a=20; |
06 | float b=20.5; |
07 | char c= 'c' ; |
08 | void *p; |
09 | |
10 | p=&a; |
11 | printf ( "%d" ,*(( int *)p)); |
12 | |
13 | p=&b; |
14 | printf ( "\n%f" ,*(( float *)p)); |
15 | |
16 | p=&c; |
17 | printf ( "\n%c" ,*(( char *)p)); |
18 | } |
Output
0 comments:
Post a Comment