SELF REFERENCIAL STRUCTURES Self referential structures contain a pointer member thatpoints to a structure of the same structuretype. In other words, a self-referential C structure is the one which includes a pointer to an instance of itself.
Syntax of Self-Referential Structure in C Programming struct demo { Data_type member1, member2; struct demo *ptr1,*ptr2; } struct student { int rollno ; char name[20]; struct student* link; };
As you can see in the syntax , link is a structure pointer that is pointing to the structure student , so structure student 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 struct student { int rollno ; char name[20]; struct student* link; };
Link type as is a pointer member that points to a structure ofthe same the one being declared. is referred to as a link. Links can tie one node to another node .
The concept of linked lists ,, stacks,queues , trees and manyothers works on the principle of self-referentialstructures.
#include < stdio.h > #include < conio.h > #include< string.h > struct student { int rollno ; char name[20]; struct student* link; }; An example of Self-Referential Structure in C
An other example of Self-Referential Structure in C #include<stdio.h> #in c l ud e <std l ib.h> struct node //structure of the node in the list { int info; struc t n o d e * link; };
int main() { int choice; typedef struct node NODE; NODE *PTR, *START; START = NULL;//Initialising START to NULL / / clrscr(); while(1) { printf("\n1.Enter the new node at the start\n"); printf("2.Display the elements of the list\n"); printf("3.Exit\n"); printf("Enter Choice\n"); scanf("%d",&choice);
switch(choice) { case 1:PTR = (NODE*)malloc(sizeof(NODE)); //Allocating Memory to new node printf("Enter the number you want to enter at the start\n"); scanf("%d",&PTR->info); if(START == NULL) { START = PTR;
PTR->link = NULL; } else { PTR->link = START; START = PTR; } break; case 2:PTR = START; printf("The elements in the list are::\n"); while(PTR->link != NULL)
{ printf("%d\t",PTR->info);PTR = PTR->link;} print f ( " % d",PT R -> i nf o ); break; case 3:exit(1); break; default: printf("\nEnter ValidChoice"); } } return 0; }