Void pointer is a generic pointer that can be used to point another variable of any data type. Null pointer is a pointer which is pointing to nothing.
In C programming, void pointers and null pointers serve different purposes. A void pointer is used when the data type of the object being pointed to is unknown or can vary, while a null pointer is used to indicate that a pointer is not pointing to any valid memory location.
A void pointer (also called a generic pointer) can store the address of any data type.
It is declared using the void * syntax.
void *ptr;
malloc().#include
int main() {
int num = 10;
void *ptr = #
printf("%d", *(int *)ptr);
return 0;
}
Since a void pointer does not know the type of data it points to, it must be typecast before dereferencing.
A null pointer is a pointer that does not point to any valid memory location.
It is assigned the value NULL.
int *ptr = NULL;
#include
int main() {
int *ptr = NULL;
if (ptr == NULL) {
printf("Pointer is not pointing to any memory location.");
}
return 0;
}
| Void Pointer | Null Pointer |
|---|---|
| Can point to any data type. | Points to no valid memory location. |
Declared using void *. |
Assigned using NULL. |
| Requires typecasting before dereferencing. | Cannot be dereferenced safely. |
| Used for generic programming. | Used to represent an empty or invalid pointer. |
A void pointer is used when a pointer needs to handle different types of data, while a null pointer is used to indicate that a pointer currently does not reference any valid memory location. Both are important concepts for safe and efficient memory management in C programming.