A pointer to void is used to hold references to any data type. It has two properties:
- Pointer to void has the same representation and memory alignment as pointer to char.
- Pointer to void is never equal to another pointer but two void pointers assigned to a NULL are equal. The behavior of void pointers is system dependent.
We can assign any pointer to a pointer to void. We must be careful when we cast an arbitrary pointer to a pointer to void because there is nothing that prevents you from casting it to a different pointer type afterwards.
int main(void)
{
int number;
int *ptr;
void *ptrvoid;
printf("Address of ptr: %p\nAdress of ptrvoid %p\n", ptr, ptrvoid);
number = 10;
ptrvoid = &number;
printf("Adress of ptrvoid %p\n", ptrvoid);
ptr = (int *)ptrvoid;
printf("Address of ptr: %p\nAdress of ptrvoid %p\nValue pointed to by a pointer variable ptr: %d\n", ptr, ptrvoid, *ptr);
return (0);
}
Terminal$ gcc PointerToVoid.c
Terminal$ ./a.out
Address of ptr: 0x64
Adress of ptrvoid 0x1000
Adress of ptrvoid 0x7ffc8d6da404
Address of ptr: 0x7ffc8d6da404
Adress of ptrvoid 0x7ffc8d6da404
Value pointed to by a pointer variable ptr: 10
We can use sizeof operator with a pointer to void as shown below:
size_t size = sizeof(void*);
Size_t is a data type that is used for size of an object as a number of bytes. It is generally equivalent to unsigned int and is contained in header files stddef.h or stdio.h.
Sources:
[1] Understanding and Using C Pointers by Richard Reese (O’Reilly). Copyright 2013 Richard Reese, Ph.D. 978-1-449-34418-4
[2] PRINZ, Peter a Ulla KIRCH-PRINZ. C Pocket Reference. O’REILLY, 2003. ISBN 978-0-596-00436-1.