Generic pointer in c programming

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<stdio.h>
#include <malloc.h>
int main(){

void *ptr;
printf("%d",*ptr);

return 0;
}

Output: Compiler error

2. We can find the size of generic pointer using sizeof operator.

#include <string.h>
#include<stdio.h>
int main(){
void *ptr;
printf("%d",sizeof(ptr));

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<stdio.h>
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;
}

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));



Generic pointer
Null pointer
Wild pointer
Dangling pointer
Near pointer
Far pointer
Graphics video memory
Text video memory
Huge pointer
Memory model in C
C tutorial

3 comments:

SOHAN said...

its very goooooooooddddddddddddd

Arun Gupta said...

please..check the point no.4 in the post ..it should be typecast before
assigning to any type of pointer

Anandrao Sakhare said...

point 4.
It will Generate an Warning..assignment from an incompatible pointer type