Null Pointer in C

A null pointer in C is a pointer that doesn't point to any valid memory location. It is commonly used to indicate that a pointer has not been initialized or that it is meant to point to nothing. The null pointer is often used as a sentinel value in C programming to signify that a pointer is invalid or uninitialized.

Definition

A null pointer is a pointer that is assigned a value of NULL, indicating that it does not point to any memory location. It is important to check for null pointers before dereferencing them to prevent errors or undefined behavior.

The syntax for initializing a null pointer is:

Syntax:

                        
pointer_name = NULL;
                        
                    

Example: Null Pointer

This example demonstrates how to initialize a null pointer, check if it is null, and how to avoid dereferencing a null pointer.

Example Code:

                        
#include <stdio.h>
int main() 
{
   int *ptr = NULL;  // Null pointer initialization
        
   if (ptr == NULL) {
        printf("The pointer is null, it doesn't point to any valid memory location.\n");
    } else {
        printf("Dereferencing the pointer: %d\n", *ptr);  // This would cause an error if ptr is null
    }
    return 0;
}
                        
                    

Output

The pointer is null, it doesn't point to any valid memory location.

Key Points