Null Pointer in C

Written by

Namrata Jangid

Null Pointers :

A null pointer points to nothing. It is assigned the value NULL, therefore it is called the null pointer.
If you do not want the pointer to store any address then assign it to NULL.
The syntax for creating a Null pointer is:

type *pointerName = NULL;
  • type is the type of the pointer variable. It should be a valid data type in C.
  • pointerName is the name of the pointer variable.

For example:

int *intPtr = NULL;
char *charPtr = NULL;

Let us look at a code snippet to understand Null pointers.

#include <stdio.h>
 
int main () {
 
int  *intPtr = NULL;
 
printf("Value of intPtr is : %x\n", intPtr  );
 
return 0;
}

In this code we are creating a Null pointer of int type. When we run this code, we get the following output:

Value of intPtr is : 0

The Null pointer is a constant with value zero in several standard libraries. We get the output as 0, which indicates that the pointer does not intend to point to any accessible memory location i.e. it intends to point to nothing.
It is important to remember that a Null Pointer is different from a dangling pointer or an uninitialized pointer. Both dangling and uninitialised pointers may point to an accessible memory location even though they are invalid. However, a null pointer is valid and it will never point to an accessible memory location.
A null pointer has several uses:

  • To initialise a pointer variable when that pointer variable is not assigned any valid memory address yet
  • To pass a null pointer to a function argument when we do not want to pass any valid memory address.
  • To check for null pointer before accessing any pointer variable. This is done for error handling purposes. We should always check if a pointer is null before some operations.

Null Pointer in C