The ones who are crazy enough to think they can change the world are the ones who do.- Steve Jobs
C programming doesn't provide any generic pointer to pointer type. Instead it provides generic pointer type called void pointer. Thus void pointer is most commonly called as general purpose pointer.
Void pointer is alone generic because void pointer does not have any associated data type with it. Being generic void pointer can store address of a variable irrespective of it's datatype.
The purpose of void pointer is awesome, let us consider that we have to declare three pointer variables of three different type say char*, int* and float* if we have no idea about void pointer we definitely going to declare three pointer variable with particular datatypes. Now your code looks like superfluous with datatypes, to overcome this drawbacks void* was introduced. when you declare a pointer variable of type void a conversions to a particular datatypes are applied automatically by the compiler i.e) if the value of a address stored in a void pointer is int datatype then void will convert into int type automatically at the time of compilation. If typecasting is not made, the compiler won't have any idea about what datatype the address in the void pointer points to.
void *variable_name;
Dereferencing pointer variable of void type is bit complex than usual pointer variable. Consider the following program which will not compile .
#include <stdio.h> int main() { int i = 5; void *vptr; // void pointer declaration vptr = &i; printf("\nValue of iptr = %d ", *vptr); return 0; }
While Dereferencing a pointer variable of void type typecasting is necessary. Consider the following program which will compile.
#include <stdio.h> int main() { int i = 5; void *vptr; // void pointer declaration vptr = &i; printf("\nValue of iptr = %d ", *(int *)vptr); return 0; }
The void pointer "vptr" is initialized by the address of integer variable 'i'. So, the value must be referred using typecast. If you try to access the data without typecasting, the compiler will show an error.
#include <stdio.h> int function(); // function declaration int main() { char *ptr = "void pointer to string"; void *vptr; // void pointer declaration vptr = &ptr; printf("%s" , *(char **)vptr); return 0; }
In the above program pointer to pointer typecasting *(char **)vptr is done to retrieve the string stored in a character pointer variable using void pointer.
We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.
© Copyright 2019