Programming in C: Unit III (b): Pointers

Generic Pointers

with Example C Programs

A generic pointer is a pointer variable that has void as its data type. The void pointer, or the generic pointer, is a special type of pointer that can be used to point to variables of any data type. It is declared like a normal pointer variable but using the void keyword as the pointer's data type.

GENERIC POINTERS

A generic pointer is a pointer variable that has void as its data type. The void pointer, or the generic pointer, is a special type of pointer that can be used to point to variables of any data type. It is declared like a normal pointer variable but using the void keyword as the pointer's data type. For example,

Programming Tip: A compiler error will be generated if you assign a pointer of one type to a pointer of another type without a cast.

void *ptr;

In C, since you cannot have a variable of type void, the void pointer will therefore not point to any data and thus cannot be dereferenced. You need to type cast void pointer (generic pointer) to another kind of pointer before using it.

Programming Tip: A pointer variable of type void * cannot be dereferenced.

Generic pointers are often used when you want a pointer to point to data of different types at different times. For example, look at the code given below.

#include <stdio.h>

int main()

{

int x=10;

char ch = 'A';

void *gp;

gp = &x;

printf("\n Generic pointer points to the integer value = %d", *(int *) gp);

gp = &ch;

printf("\n Generic pointer now points to the character = %c", (char*) gp);

return 0;

}

Output

Generic pointer points to the integer value = 10

Generic pointer now points to the character = A

It is always recommended to avoid using void pointers unless absolutely necessary, as they effectively allow you to avoid type checking.

Programming in C: Unit III (b): Pointers : Tag: : with Example C Programs - Generic Pointers