Creating the head pointer
What you'll learn: How to declare the entry point for a linked list to ensure your program doesn't lose track of your data.
The anchor of your list
Imagine you are holding a long string of paperclips. Each paperclip represents a "node" containing data. If you drop the first paperclip, the entire chain falls onto the floor and disappears into the vents.
In C, a linked list is exactly like that chain. The nodes are scattered across your computer's memory. The only way to find the list is by holding onto the very first link. This "handle" is what we call the head pointer.
Defining the pointer
The head pointer is not a node itself; it is a variable that stores the memory address of the first node. Because it points to a structure, its type must match the struct you created for your nodes.
If you don't have a first node yet, the head pointer should point to NULL. This tells C, "I have a list started, but it is currently empty."
#include <stdio.h>
#include <stdlib.h>
// Define the shape of a single link (node)
struct Node {
int data;
struct Node* next;
};
int main() {
/*
1. Create the head pointer.
2. Initialize it to NULL because the list is empty.
*/
struct Node* head = NULL;
if (head == NULL) {
printf("The list is currently empty. The anchor is set!\n");
}
return 0;
}
Why initialization matters
Declaring struct Node* head; without setting it to NULL is dangerous. In C, uninitialized pointers contain "garbage" values—random memory addresses left over from other programs.
If you try to read an uninitialized head pointer, your program might think there is already a node at some random location in memory, leading to a immediate crash (Segmentation Fault). By setting it to NULL, you provide a clear signal to your functions that the list is waiting to be filled.
Key takeaway
The head pointer is the only "map" your program has to find a linked list; always initialize it to NULL to signify an empty list.