Self Referential Structure | C Tutorial

 

Let us understand what is a self-referential structure in C programming and how do we implement a self referential structure in data structures.

Before we go ahead with self-referential data structures, let us also have a look at what are structures and in case you know it, you can skip it.

 

What are Structures?

An array is a collection of homogeneous elements but in the real world, we may need to include different types of logically related data.

To store different data such as name, age, contact, etc. associated with a single entity, we make use of structures.

A structure is, therefore, capable of storing heterogeneous data under a single name and the data elements are called as members.

What is a Self-Referential Structure?

A structure that contains pointers to a structure of its own type is known as self-referential structure.

In other words, a self-referential C structure is the one which includes a pointer to an instance of itself.

   

Self Referential Structure in C programming with Insertion, Deletion, Traversal, Reverse, Adding and other opertions of Linked Lists

Syntax of Self-Referential Structure in C Programming

As you can see in the syntax, ptr1 and ptr2 are structure pointers that are pointing to the structure demo, so structure demo is a self referential structure. These types of data structures are helpful in implementing data structures like linked lists and trees.

It is an error to use a structure variable as a member of its own struct type structure or union type union, respectively.

Self Referential Structure Example

The concept of linked lists, stacks, queues, trees and many others works on the principle of self-referential structures.

   

One important point worth noting is that you cannot reference the typedef that you create within the structure itself in C programming.

Implementation of Self Referential Structure in Linked Lists

If you have any doubts or errors in the self referential data structure implementations, let us know about it in the comment section. Find more about it here.

Let's Discuss