C Tutorial C Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

C - Null Pointers



Pointers of every type have a special value known as null pointer value of that type. A pointer that is assigned NULL is called a null pointer. A pointer whose value is null does not point to an object or a function. Dereferencing a null pointer shows undefined behavior. All pointers of the same type whose value is also null compares equal.

A null pointer constant can be converted to any pointer and pointer to member type. Such conversion results in the null pointer value of that type.

To initialize a pointer to null or to assign the null value to an existing pointer, the null pointer constant NULL may be used.

Different ways of creating null pointers are given below:

//initialize a pointer to null
int *ptr1 = NULL; 
int *ptr2 = 0;

//existing pointer is assigned to null
int *ptr3;
ptr3 = NULL; 
int *ptr4;
ptr4 = 0;

Null pointers can be used to indicate the absence of an object, or as an indicator of error conditions. Normally, a function with a pointer argument generally needs to check if the value is null and handle that case differently (for example, the delete expression does nothing when a null pointer is passed).

To check for a null pointer the following statement can be used:

if(ptr)   //succeeds if ptr is not null
if(!ptr)  //succeeds if ptr is null

Example:

In the example below, a function called print is created to print the value stored in the passed pointer. The functions handles the null pointer differently and print a message in that case.

#include <stdio.h>
 
void print(int *ptr) {
  if (!ptr)
    printf("print(int*): It is null.\n");
  else
    printf("print(int*): %d\n", *ptr);
}
 
int main() {
  int x = 25;
  
  //using print function with null pointer
  int *p1 = NULL;
  print(p1);

  //using print function with pointer
  int *p2 = &x;
  print(p2); 
 
  return 0;
}

The output of the above code will be:

print(int*): It is null.
print(int*): 25

❮ C - Pointers

5