Generic pointer:
void pointer in c is known as generic pointer. Literal meaning of generic pointer is a pointer which can point type of data.
Example:
void *ptr;
Here ptr is generic pointer.
Important points about generic pointer in c?
1. We cannot dereference generic pointer.
#include
#include
#include <malloc.h>
int main(){
void *ptr;
printf("%d",*ptr);
return 0;
return 0;
}
Output: Compiler error
2. We can find the size of generic pointer using sizeof operator.
#include <string.h>
#include
#include
int main(){
void *ptr;
printf("%d",sizeof(ptr));
return 0;
return 0;
}
Output: 2
Explanation: Size of any type of near pointer in c is two byte.
3. Generic pointer can hold any type of pointers like char pointer, struct pointer, array of pointer etc without any typecasting.
Example:
#include
#include
int main(){
char c='A';
int i=4;
void *p;
char *q=&c;
int *r=&i;
p=q;
printf("%c",*(char *)p);
p=r;
printf("%d",*(int *)p);
return 0;
return 0;
}
Output: A4
4. Any type of pointer can hold generic pointer without any typecasting.
5. Generic pointers are used when we want to return such pointer which is applicable to all types of pointers. For example return type of malloc function is generic pointer because it can dynamically allocate the memory space to stores integer, float, structure etc. hence we type cast its return type to appropriate pointer type.
Examples:
1.
char *c;
c=(char *)malloc(sizeof(char));
2.
double *d;
d=(double *)malloc(sizeof(double));
3.
Struct student{
char *name;
int roll;
};
Struct student *stu;
Stu=(struct student *)malloc(sizeof(struct student));
No comments:
Post a Comment