What is a Null Pointer in C Language
Categories: C language
A Null Pointer is a pointer that does not point to any memory location. It stores the base address of the segment. The null pointer basically stores the Null value while void is the type of the pointer.
A null pointer is a special reserved value which is defined in a stddef header file. Here, Null means that the pointer is referring to the 0th memory location. If we do not have any address which is to be assigned to the pointer, then it is known as a null pointer. When a NULL value is assigned to the pointer, then it is considered as a Null pointer.
Applications of Null Pointer
Following are the applications of a Null pointer:
1. It is used to initialize o pointer variable when the pointer does not point to a valid memory address.
2. It is used to perform error handling with pointers before dereferencing the pointers.
3. It is passed as a function argument and to return from a function when we do not want to pass the actual memory address.
Examples of Null Pointer
int *ptr=(int *)0;
float *ptr=(float *)0;
char *ptr=(char *)0;
double *ptr=(double *)0;
In the above code, we declare the pointer variable *ptr, but it does not contain the address of any variable. The dereferencing of the uninitialized pointer variable will show the compile-time error as it does not point any variable. According to the stack memory concept, the local variables of a function are stored in the stack, and if the variable does not contain any value, then it shows the garbage value. The above program shows some unpredictable results and causes the program to crash. Therefore, we can say that keeping an uninitialized pointer in a program can cause serious harm to the computer. In the above code, we create a pointer *ptr and assigns a NULL value to the pointer, which means that it does not point any variable. After creating a pointer variable, we add the condition in which we check whether the value of a pointer is null or not.