Self Referential Structure in C: Definition and Example
self referential structure in C is a structure that contains a pointer to the same type of structure within itself. This allows the creation of linked data structures like linked lists, where each element points to the next one.How It Works
Imagine a chain where each link holds a reference to the next link. A self referential structure works the same way in C. It is a structure that has a member which is a pointer to another structure of the same type. This pointer allows the structure to connect to another instance of itself, forming a chain or network.
This is useful because it lets you build flexible data collections like linked lists, trees, or graphs. Instead of storing all data in one big block, each structure points to the next, making it easy to add, remove, or rearrange elements.
Example
This example shows a simple self referential structure for a linked list node holding an integer value and a pointer to the next node.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next; // Pointer to the next node of the same type
};
int main() {
struct Node node1, node2;
node1.data = 10;
node1.next = &node2; // node1 points to node2
node2.data = 20;
node2.next = NULL; // node2 is the last node
// Print the linked list values
struct Node* current = &node1;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
return 0;
}When to Use
Use self referential structures when you need dynamic and flexible data collections that can grow or shrink during program execution. Common uses include:
- Linked lists, where each element points to the next.
- Trees, where each node points to child nodes.
- Graphs, where nodes connect to multiple others.
These structures help manage memory efficiently and allow easy insertion or deletion of elements without reorganizing the entire data set.
Key Points
- A self referential structure contains a pointer to its own type.
- This pointer enables linking multiple structures together.
- It is essential for building linked lists, trees, and other dynamic data structures.
- Helps manage data that changes size during runtime.