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.


void *ptr;
Here ptr is generic pointer.

Important points about generic pointer in c?

1. We cannot dereference generic pointer.

#include <malloc.h>
int main(){

void *ptr;

return 0;

Output: Compiler error

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

#include <string.h>
int main(){
void *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.


int main(){

char c='A';
int i=4;
void *p;
char *q=&c;
int *r=&i;

printf("%c",*(char *)p);

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.


char *c;
c=(char *)malloc(sizeof(char));

double *d;
d=(double *)malloc(sizeof(double));

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
Post a Comment