Self-Referential Structures in C
A self-referential structure is a structure that contains a pointer to a structure of the same type as itself.
This is the fundamental building block for creating dynamic data structures such as:
- Singly Linked List
- Doubly Linked List
- Circular Linked List
- Binary Trees
- Graphs (adjacency list)
- Hash table chaining
1. Basic Declaration of Self-Referential Structure
There are two common ways to declare it:
Method 1: Using structure tag (most common & recommended)
C
Standard way
struct Node {
int data;
struct Node* next; // pointer to same type
};
Method 2: Using typedef (cleaner to use)
C
Using typedef
typedef struct node {
int data;
struct node* next;
} Node;
// Now you can write: Node* head;
2. Simple Example - Creating a Linked List Node
C
Creating and linking 3 nodes
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* next;
} Node;
int main() {
Node* head = NULL;
Node* second = NULL;
Node* third = NULL;
// Allocate memory
head = (Node*)malloc(sizeof(Node));
second = (Node*)malloc(sizeof(Node));
third = (Node*)malloc(sizeof(Node));
// Assign data
head->data = 10;
second->data = 20;
third->data = 30;
// Link them
head->next = second;
second->next = third;
third->next = NULL;
// Print list
Node* temp = head;
while(temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
return 0;
}
3. Most Common Real-World Uses
| Data Structure | Self-Referential Pointers Used | Typical Name |
|---|---|---|
| Singly Linked List | next | next / link |
| Doubly Linked List | next + prev | next, prev |
| Circular Singly List | next (last → first) | next |
| Circular Doubly List | next + prev (last ↔ first) | next, prev |
| Binary Tree | left + right | left, right |
| Graph (Adjacency List) | next (for each neighbor) | next |
4. Best Practices & Common Mistakes
- Always initialize pointers to NULL
- Check for malloc() failure
- Never access ->next/data on NULL pointer
- Use typedef to make code cleaner
- Free memory when deleting nodes (avoid memory leaks)
- Common error: forgetting to update links when inserting/deleting
Codecrown