Void pointer or generic pointer is a special type of pointer that can be pointed to objects of any data type. A void pointer is declared like a normal pointer, using the void keyword.
Pointers defined using specific data type cannot hold the address of the some other type of variable.
You should use it when you do not know what data type the memory contains. The advantage is that once you know the data type, you may typecast the void pointer into the appropriate data type.
A good example is the "malloc" function. It returns a void* and you can typecast it to whatever type you need.
void *malloc(size_t size);
Pointers defined using specific data type cannot hold the address of the some other type of variable.
You should use it when you do not know what data type the memory contains. The advantage is that once you know the data type, you may typecast the void pointer into the appropriate data type.
A good example is the "malloc" function. It returns a void* and you can typecast it to whatever type you need.
void *malloc(size_t size);
int *n = (int *) malloc(sizeof(int));
Example:
void *v;
int *i;
int ivar;
char chvar;
float fvar;
v = &ivar; // valid
v = &chvar; //valid
v = &fvar; // valid
i = &ivar; //valid
i = &chvar; //invalid
i = &fvar; //invalid
Example:
void *v;
int *i;
int ivar;
char chvar;
float fvar;
v = &ivar; // valid
v = &chvar; //valid
v = &fvar; // valid
i = &ivar; //valid
i = &chvar; //invalid
i = &fvar; //invalid
No comments:
Post a Comment