Course contentsShow
← C
Lesson 627 of 1,2199. Structures and UnionsFree lesson

Limitations of self-referential definitions

Limitations of self-referential definitions

What you'll learn: Why a structure cannot contain an instance of itself directly, but must use pointers instead.

The infinite box paradox

Imagine you are designing a physical box. You decide that inside this box, there must be another box of the exact same size. If you try to build this, you quickly realize it is physically impossible. To fit a second box inside the first, the outer box would have to be larger than itself. If the inner box also contains a third box of the same size, the problem repeats forever.

In C, structures face the same physical limitation. When you define a struct, the compiler needs to know exactly how many bytes of memory to set aside for it. If a struct Node contains a struct Node member, the compiler calculates the size as: "Size of an integer + Size of a Node." But to find the size of that "Node," it needs to add "Size of an integer + Size of a Node" again. This creates an infinite loop, and the compiler will throw an error because the size of the structure is effectively infinite.

Using a "Map" instead

To fix this, we don't put the box inside the box; we put a post-it note inside the box. In C, that post-it note is a pointer. A pointer has a fixed, known size (usually 4 or 8 bytes) regardless of what it points to.

By using a pointer, the compiler can successfully calculate the structure's size. It knows the size of the basic data types plus the fixed size of the memory address (the pointer).

// This will FAIL: Infinite size
struct IllegalNode {
    int data;
    struct IllegalNode next; 
};

// This will WORK: Fixed size
struct LegalNode {
    int data;
    struct LegalNode *next; // A pointer to the next node
};

Why this matters

This limitation is why every linked list, tree, or graph you build in C relies on pointers. A "Node" in a linked list doesn't actually hold the next node; it holds the address of where the next node lives in memory. This allows your data structures to grow dynamically without violating the rules of memory allocation.

Key takeaway

A structure cannot contain an actual instance of itself because its size would be undefined; it must use a pointer to reference itself.