Nearby lessons

91 of 124

C - NULL Pointer

NULL Pointer is one of the foundational topics in C programming. This lesson explains Complete Program 5 — Safe Use with NULL with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Complete Program 5 — Safe Use with NULL

Always check that a pointer is not NULL before using *p — this avoids the famous segmentation fault (crash) that happens when you dereference a pointer holding an invalid address.

Example01
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 int a = 10;
6 int *p = NULL; // points to nothing - safe starting state
7 
8 if (p != NULL) {
9 printf("%d\n", *p);
10 } else {
11 printf("p is NULL - nothing to print\n");
12 }
13 
14 p = &a; // now p really points to a
15 if (p != NULL) {
16 printf("Now *p = %d\n", *p);
17 }
18}
Output
p is NULL - nothing to print Now *p = 10
📝 Key Takeaways
  • A pointer stores the address of a variable; it 'points to' it.
  • & gives the address; * gives the value at an address.
  • Each concept has its own program: & and *, change via pointer, arrays, swap, NULL.
  • Array name = address of the first element; *(p+i) walks the array.
  • Call by reference uses & and * so a function can change original variables.
  • Swap is the classic call-by-reference example.
  • Always check for NULL before using a pointer.
  • (Advanced pointer topics — pointers to functions, linked lists — are beyond beginner scope.)

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1