VOID POINTERS
Pointers can also be declared as void type. Void pointers cannot
be dereferenced without explicit type conversion. This is
because, being void the compiler cannot determine the size of
the object that the pointer points too. Though void pointer
declaration is possible, void variables declaration is not
allowed. Thus, the declaration void P displays an error message.
"size of ‘p’ is unknown or zero", after compilation.
PROGRAM:
Write a program to declare a void pointer. Assign address of
int, float and char variables to the void pointer using type
casting method. Display the contents of various variables.
#include<stdio.h> #include<conio.h> Void main() { int p; float d; char c; void *ptr; clrscr(); pt=&p; *(int*)pt=10; printf("\n p=%d",p); pt=&d; *(float *)pt=3.4; printf("\n d=%f",d); pt=&c; *(char *)pt= ‘s’; printf("\n c=%c",c); getch(); }
O/P:
p=10
d=3.4
c=s
In the above
example, the statement *(int *)pt=10 assigns the integer value
10 to pointer pt i.e., to variable ‘p’. the declaration *(int *)
tells the compiler that the value assigned is of integer type.
Thus, assignments of float and char type are carried out. The
statements *(int *)pt=10, *(float *)pt=3.4, *(char *)pt=’s’
helps the compiler to exactly determine the size of data type.