Coupon Accepted Successfully!


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 to. Though void pointer declaration is possible, void variable declaration is not allowed. Thus, the declaration void p will display an error message “Size of ‘p’ is unknown or zero” after compilation.
It is not possible to declare void variables such as pointers. A pointer points to an existing entity. A void pointer can point to any type of variable with proper type casting. The size of the void pointer displayed will be two. When a pointer is declared as void, two bytes are allocated to it. Later, using type casting, the number of bytes can be allocated or de-allocated. void variables cannot be declared, because memory is not allocated to them, and there is no place to store the address. Therefore, void variables cannot actually serve the purpose they are made for.


13.7 Write a program to declare a void pointer. Assign address of intfloat, and char variables to the void pointer using typecasting method. Display the contents of various variables.

// void pointers //




int p;

float d;

char c;

void *pt = &p; // pt points to p

void main (void)



*(int *) pt = 12;

cout<<“\n p=”<<p;

pt = &d; // pt points to d

*(float *)pt = 5.4;

cout<<“\n r=”<<d;

pt=&c; // pt points to c

*(char* )pt=‘S’;

cout<<“\n c=”<<c;







Explanation: In the above example, variables pd, and c are variables of type int, float, and char, respectively. Pointer pt is a pointer of type void. These entire variables are declared before main(). The pointer is initialized with the address of integer variable p, that is, the pointer p points to variable x.
The statement *(int *) pt = 12 assigns the integer value 12 to pointer pt, that is, to a variable p. The contents of the variable p are displayed using the succeeding statement. The declaration *(int *) tells the compiler that the value assigned is of integer type. Thus, the assignment of float and char type is carried out. The statements *(int *) pt = 12*(float *) pt = 5.4, and *(char*) pt = ‘S’ help the compiler exactly determine the size of data type.

Test Your Skills Now!
Take a Quiz now
Reviewer Name