Null Pointer in C Language
0 330
The Pointer that does not point to any memory address is called a null pointer.
A null pointer is a pointer that has the value 0 or null.
usually, another Pointers holds memory address pointing data.
The Null pointer does not point anywhere.
It is important to handle the null pointer carefully to avoid runtime errors.
They are useful for Initialization and error checking.
null pointers are commonly used to indicate the absence of a valid pointer target.
common uses of null pointers in C
Initialization: Null pointers are often used to initialize pointers before they are assigned valid memory addresses.
For example:
int *ptr = NULL;Error Handling: Null pointers are frequently used to indicate errors or exceptional conditions, especially in functions that return pointers. For instance, many standard library functions return a null pointer to signal failure.
For example:
FILE *file = fopen("nonexistent_file.txt", "r"); if (file == NULL) { printf("Error: File not found!\n"); }Termination: In data structures like linked lists, trees, and graphs, null pointers are used to terminate the structure.
For example, in a linked list, the last node's pointer typically points to null, indicating the end of the list.
Dynamic Memory Allocation: Null pointers are often used to initialize pointers before allocating memory dynamically.
After memory allocation, the pointer is updated to point to the allocated memory.
For example:
int *dynamic_ptr = NULL; dynamic_ptr = (int *)malloc(sizeof(int));Function Pointers: Null pointers can be used in function pointers to indicate that they don't currently point to any function.
This can be useful for initializing or resetting function pointers.
For example:
void (*func_ptr)(int) = NULL;
Syntax of Null pointer in C
// Using the constant NULL dataType *ptr = NULL; // Using the literal 0 dataType *ptr = 0;
Example:
#include<stdio.h> int main() { int *p = NULL; if (p == NULL) { printf("Pointer is NULL\n"); } else { printf("Pointer is not NULL\n"); return 0; } }Output:
Pointer is NULL
Share:
Comments
Waiting for your comments