Self-Referential Structures in C
A self-referential structure is a structure that contains a pointer to another structure of the same type. This allows structures to be chained together, forming dynamic data structures like linked lists, trees, and graphs. In simple terms: one member of the structure points to another variable of the same structure type.Syntax
Example: Two Linked Nodes
Visualising the Link
n1.next holds the address of n2. Accessing n1.next->data gives 20.
Why Self-Referential Structures Matter
They are the foundation of:| Data Structure | Description |
|---|---|
| Singly Linked List | Each node points to the next |
| Doubly Linked List | Each node points to both next and previous |
| Binary Tree | Each node has left and right child pointers |
| Graph (Adjacency List) | Each node has a list of neighbour pointers |
Key Points
- The pointer member must be
struct NodeName *— a pointer to the same struct type - You cannot embed a struct inside itself (that would be infinite size), but a pointer to itself is fine
- The last node in a chain always has its pointer set to
NULL