Course contentsShow
← C
Lesson 989 of 1,21914. Data Structures in CFree lesson

Defining the self-referential node struct

Defining the self-referential node struct

What you'll learn: How to create a structure that can point to another version of itself to build a chain of data.

The problem with arrays

Arrays are like a row of lockers built into a wall. They are stuck in a fixed sequence, and you can’t easily squeeze a new locker between two existing ones. If you want a data structure that can grow and shrink dynamically, you need a Linked List.

A linked list is like a scavenger hunt. Instead of all items being in one row, each item is in its own box. Inside that box, there is a piece of data and a "map" (a pointer) telling you exactly where the next box is located.

Creating the "Node"

To build this, we use a struct. In a linked list, each individual link is called a node. A node needs to store two things:

  1. The actual information (like an integer or a character).
  2. The address of the next node in the sequence.

This leads to a unique C programming concept called a self-referential structure. It’s a struct that contains a pointer to the same type of struct.

The Syntax

Here is how we define a node for a list of integers:

struct Node {
    int data;            // The value we want to store
    struct Node *next;   // A pointer to the next Node in the list
};

Wait—how can we use struct Node inside its own definition?

Think of it like a set of directions. The next pointer isn't containing a whole other node inside itself (which would be impossible, like a box containing a box of the same size). Instead, it is just a small memory address. It is simply saying, "If you want the next piece of data, go to this specific house number in memory."

Why the asterisk matters

The *next is crucial. Without the asterisk, the compiler would get confused trying to calculate the size of the struct, leading to an infinite loop of definitions. By using a pointer, the compiler knows exactly how much space to set aside for an address, allowing us to link these nodes together like a chain, regardless of where they are in your computer's memory.

Key takeaway

A self-referential struct uses a pointer to connect one instance of a data type to another, forming the foundation of a Linked List.