Join Regular Classroom : Visit ClassroomTech

Void pointer in C

Void pointer is a generic pointer, it has void as its dataype. It can hold the address of any datatype. While dereferencing through void pointer typecasting is must. In c malloc() and calloc() functions return void pointer. The size of the void pointer in C is the same as the size of the pointer of character type.

Why we use void pointer?
Till now, we have studied that the address assigned to a pointer should be of the same type as specified in the pointer declaration.

For example, if we declare the int pointer, then this int pointer cannot point to the float variable or some other type of variable i.e. it can point to only int type variable. To overcome this problem, we use a pointer to void. Let’s see an example.

#include<stdio.h>

int main() {
	int x=10;
	char ch="A";
	void *gp;                  //it is a generic pointer
	gp=&x;                    //address of int variable x is stored in gp
	printf("%d",*(int*)gp);    //explicit typecasting it convert gp to integer pointer
	gp=&ch;                   // address of char variable ch is stored in gp
	printf("%c",*(char*)gp);
	return 0;
}

Now what is *(int*)gp in above program? Let’s break it step by step:

1. *(int*)gp
2. *(int pointer gp)
3. value at integer pointer gp
4. value at &x which is 10

Points to remember

1. The void pointer in C cannot be dereferenced directly. Let’s see the below example.

#include <stdio.h>  
int main() {  
	int x=80;  
	void *p;  
	p=&x;  
	printf("Value which is pointed by ptr pointer : %d",*p);  
	return 0;  
}  

In the above code, *p is a void pointer which is pointing to the integer variable ‘x’. As we already know that the void pointer cannot be dereferenced, so the above code will give the compile-time error because we are printing the value of the variable pointed by the pointer ‘p’ directly.

So, how to overcome the problem?

#include <stdio.h>  
int main() {  
	int x=80;  
	void *p;  
	p=&x;  
	printf("Value which is pointed by ptr pointer : %d",*(int*)p);  
	return 0;  
}  

In the above code, we typecast the void pointer to the integer pointer by using the statement (int*)p. Then, we print the value of the variable which is pointed by the void pointer ‘ptr’ by using the statement *(int)*ptr

Output:
Value which is pointed by ptr pointer : 80

2. We cannot apply the arithmetic operations on void pointers in C directly. We need to apply the proper typecasting so that we can perform the arithmetic operations on the void pointers.

3. It is always recommended to avoid the using of void pointers unless it is urgent as they effectively allow you to avoid type checking.


You Missed

Also Checkout