What is Null Pointer in C: Explanation and Example
null pointer is a pointer that does not point to any valid memory location and is usually set to NULL. It acts as a special marker to indicate that the pointer is empty or uninitialized.How It Works
A null pointer in C is like an empty signpost that points nowhere. When you declare a pointer, it usually holds the address of some variable or memory. But if you set it to NULL, it means the pointer is intentionally made to point to nothing.
This helps programmers avoid mistakes by checking if a pointer is NULL before using it. If you try to use a null pointer to access memory, the program will usually crash or behave unpredictably, which is why it is important to check.
Example
This example shows how to declare a null pointer and check it before use.
#include <stdio.h> int main() { int *ptr = NULL; // ptr is a null pointer if (ptr == NULL) { printf("Pointer is null and safe to check.\n"); } else { printf("Pointer is not null.\n"); } return 0; }
When to Use
Use null pointers to indicate that a pointer does not currently point to any valid data. This is useful when you want to show that a pointer is empty or uninitialized.
For example, when a function returns a pointer but fails to find the requested data, it can return NULL to signal "no result." Also, before using a pointer, checking if it is NULL helps prevent errors and crashes.
Key Points
- A null pointer points to nothing and is set using
NULL. - It helps detect uninitialized or empty pointers safely.
- Always check if a pointer is
NULLbefore dereferencing it. - Using a null pointer without checking causes program crashes.