Originally Posted on SeedBx
Welcome
to the sixth part of the Gentle Introduction to C series. As said
before this series aims to provide you a brief introduction to C language.
In this part we will be talking about a specific and
special pointer, void pointer.
void Pointer
Each pointer has a data-type associated with it
which specifies about the type of variable which the pointer will point to. A
void pointer, unlike others, is a pointer which has no data-type associated
with it. Due to this, a void pointer can be used to hold memory address of any
data-type and can be type casted into any type.
Example -
void *ptr;
int a=1;
ptr=&a;
char c=’z’;
ptr=&c;
As shown in the above example, the void pointer
variable ‘ptr’ is at first, used to store the memory address of an int variable
‘a’ and later used to store the memory address of char variable ‘c’.
Uses :
- malloc() and calloc() functions, which are used to dynamically allocate memory, return a void pointer allowing these functions to be used to allocate memory for any data-type.
Example -
int *a=malloc(sizeof(int)*n);
In the above example, we have used malloc() to dynamically allocate memory for an int type array ‘a’ of size ‘n’. This behaviour is only possible due to the fact that malloc() returns a void pointer.
Note : The above example will not work with C++, as it requires the return void pointer to be explicitly type casted to the desired type.
Hence the above example in C++ will be written as,
int *a=(int
*)malloc(sizeof(int)*n);
- void pointers are generally used to implement generic functions.
Facts :
- void pointers cannot be dereferenced.
Example-
int a=21;
void *ptr=&a;
printf(“%d, *ptr); //-(i)
printf(“%d,
*(int *)ptr); //-(ii)
In the example given above, the printf() function at line-(i) will give an error like “Compiler Error : ‘void*’ is not a pointer-to-object type”. However if we run the program without line-(i), the printf() function at line-(ii) will display the value of the int variable ‘a’, which is 10, due to the fact that void pointer variable ‘ptr’ was explicitly type-casted into an int pointer.
- The C-Standard doesn’t allow pointer arithmetic with void pointers.
Note : In GNU C pointer arithmetic is allowed by considering the size of void to be 1. However this might not be the case with other compilers.
At last, void pointers provide a sense of generality
in the field of pointers. However this freedom is often accompanied by certain
restrictions to make things efficient and let operations be under control.
Thanks
for reading.
As
usual your suggestions and feedback are always welcome.
Also See : Pointers, Function, extern Keyword
No comments:
Post a Comment