int *p,a; char b; p=&a; //valid 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.
void *p; int a; char b; p=&a; //valid 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.
void *p; int a=20,b; p=&a; b=*p; //this will show an error b=*((int*)p); //type casting the pointer variable to dereference it
We can’t perform the pointer arithmetic on void pointer. Take below example.
void *p; int a=20; p=&a; p++; //this will show an error
Lets make one program to understand the concept of void pointer in C.
#include<stdio.h> void main() { int a=20; float b=20.5; char c='c'; void *p; p=&a; printf("%d",*((int*)p)); p=&b; printf("n%f",*((float*)p)); p=&c; printf("n%c",*((char*)p)); }
Output
This is all about void pointer in C. If you find any mistake or information missing in above tutorial then please mention in the comments.
Can we point an array of chars
the explantion is gud bt we can’t get the output in decimels unless we multiply it with .1