2. Suppose we have to declare integer pointer,character
pointer and float pointer then we need to declare 3 pointer
variables.
Instead of declaring different types of pointer
variable it is feasible to declare single pointer variable
which can act as integer pointer,character pointer.
void pointer (generic pointer)
2
3. Basic of void pointer
In C General Purpose Pointer is called as void Pointer.
It can store address of any type of variable
The compiler has no idea what type of object a void Pointer
really points to ?
Memory required for void pointer is 8 byte
Void pointer increment by 1 byte
It does not have any data type associated with it
3
4. Declaration of Void Pointer
void *pointer_name;
Void Pointer Example :
void *ptr; // ptr is declared as Void pointer
char cnum;
int inum;
float fnum;
ptr = &cnum; // ptr has address of character data
ptr = &inum; // ptr has address of integer data
ptr = &fnum; // ptr has address of float data
4
5. Dereferencing void pointer
We cannot directly dereference void pointer
like,
int intData=10;
void *ptr;
ptr=&intData;
printf(“%d”,*ptr);
// output: compiler warning/error
Type casting of void pointer is needed
printf(“%d”,*(int *)ptr);
//output: 10
5
6. void pointer reference to array
char string[]={“Hello World"};
void *ptr;
ptr=&string[0];
printf(“data : %sn”, (char*)ptr);
//output: data : Hello World
int data[]={1,2,3,4,5,6};
void *ptr=&data[0];
for(int i = 0; i < 6; i++)
{
printf(“%d ”,ptr);
ptr = ptr + 4; // pointing to next element in array
}
//output: 1 2 3 4 5 6 6
7. void pointer dereference from array
char string[]={“Hello world"};
void *ptr;
ptr=&string[0];
int data[]={1,2,3,4,5,6};
void *ptr=&data[0];
for(int i = 0; i < strlen(string); i++)
printf("%c",*(char *)ptr++);
//output : Hello world
for(int i = 0; i < 6; i++)
{
printf("%d ",*(int *)ptr);
ptr=ptr+4;
}
//output : 1 2 3 4 5 6
7
10. Array of void pointer
int data1 = 0, data2 = 30, data3=12;
void *ptr[3];
ptr[0]=&data1;
ptr[1]=&data2;
ptr[2]=&data3;
for(int i = 0; i < 3; i++)
printf("%dn",*(int *)p[i]);
//output: 0
30
12
10
11. void pointer as parameter of function
int num(void * vPtrData)
{
int result=*(int *) vPtrData;
return result;
}
int data=10;
void *ptr=&data;
printf("%dn",num(ptr));
//output: 10
11