Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Differentiate the NULL pointer with Void pointer in C language
In C programming, NULL pointers and void pointers are two distinct concepts that serve different purposes. A NULL pointer represents a pointer that doesn't point to any valid memory location, while a void pointer is a generic pointer type that can point to any data type but requires type casting for dereferencing.
Syntax
/* NULL Pointer */ data_type *pointer_name = NULL; /* Void Pointer */ void *pointer_name;
NULL Pointer
A NULL pointer is a pointer that doesn't point to any valid memory location. It's used to indicate that the pointer is not currently pointing to any object. NULL is typically defined as 0 or ((void*)0) in C.
Example
Here's a demonstration of NULL pointer usage −
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = NULL; // NULL pointer initialization
printf("NULL pointer value: %p<br>", (void*)ptr);
// Check if pointer is NULL before using
if (ptr == NULL) {
printf("Pointer is NULL - safe to check!<br>");
}
// Allocate memory
ptr = (int*)malloc(sizeof(int));
*ptr = 25;
printf("After allocation: %d<br>", *ptr);
free(ptr);
ptr = NULL; // Good practice: set to NULL after freeing
return 0;
}
NULL pointer value: (nil) Pointer is NULL - safe to check! After allocation: 25
Void Pointer
A void pointer is a generic pointer that can point to any data type. It cannot be dereferenced directly and must be cast to the appropriate pointer type before use.
Example
Here's how void pointers work with different data types −
#include <stdio.h>
int main() {
int num = 42;
float price = 99.99;
char grade = 'A';
void *vptr; // void pointer declaration
// Point to integer
vptr = #
printf("Integer value: %d<br>", *(int*)vptr);
// Point to float
vptr = &price;
printf("Float value: %.2f<br>", *(float*)vptr);
// Point to character
vptr = &grade;
printf("Character value: %c<br>", *(char*)vptr);
return 0;
}
Integer value: 42 Float value: 99.99 Character value: A
Key Differences
| Aspect | NULL Pointer | Void Pointer |
|---|---|---|
| Purpose | Indicates pointer points to nothing | Generic pointer for any data type |
| Value | Always 0 or NULL | Valid memory address |
| Dereferencing | Cannot be dereferenced (undefined behavior) | Must be cast before dereferencing |
| Usage | Safety checks, initialization | Generic programming, function parameters |
Conclusion
NULL pointers are used for safety and initialization, ensuring pointers don't point to invalid memory. Void pointers provide flexibility for generic programming by allowing a single pointer to work with multiple data types through proper casting.
