Nearby lessons

55 of 72

C - NULL Pointer

Learn what a NULL pointer means and why you should check a pointer before using it.

What Is a NULL Pointer?

A pointer set to NULL does not point to a valid object. It is useful when you do not have an address to store yet.

Example01
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 int *ptr = NULL;
6 
7 if (ptr == NULL)
8 {
9 printf("Pointer has no address yet");
10 }
11 
12 return 0;
13}
Output
Pointer has no address yet

Assigning an Address Later

After creating a pointer with NULL, you can assign it the address of a variable. Only use *ptr after it points to a valid variable.

Example02
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 int number = 20;
6 int *ptr = NULL;
7 
8 ptr = &number;
9 
10 if (ptr != NULL)
11 {
12 printf("Value: %d", *ptr);
13 }
14 
15 return 0;
16}
Output
Value: 20

Important Rule

Never read or write *ptr while ptr == NULL. It can cause the program to behave incorrectly or crash.

📝 Key Takeaways
  • NULL means a pointer is not pointing to a valid object.
  • A NULL pointer should not be dereferenced.
  • Check a pointer before using *ptr.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1