You are on page 1of 2

Explain with an example the self-referential structure.

A self-referential structure is one of the data structures which refer to the po inter to (points) to another structure of the same type. For example, a linked l ist is supposed to be a self-referential data structure. The next node of a node is being pointed, which is of the same struct type. For example, typedef struct listnode { void *data; struct listnode *next; } linked_list; In the above example, the listnode is a self-referential structure next is of the type sturct listnode because the *

Self-Referential Structures are one of the most useful features that I can think of in a programming language such as C. They allow you to create data structure s that contain references to data of the same type as themselves. They are also designed to make people who are just learning how to program cry, alot. From these people you get questions such as "how can a struct of type foo contain a reference to a variable of type foo in its own delcaration"? The corre ct answer to this is "because it can". They also allow you to do interesting things with functions that call themselves , although this can be done without self-referential structures they tend to be more usefull with them. For a simple example let's look at some code for a linked list of ints typedef struct linklist { int data; struct linklist *next; } linklist; Although this makes perfect sense to anyone who does alot of coding, it will alm ost always make a newbie coder look at it in horor. But maybe not as much horor as the following... This is a very simple function that searches through a linked list using the str uct above and returning true if the number is in the list, otherwise false. int list_search(int search, linklist *list) { int ans; if(list == NULL) ans = 0; else { if(search == list->data) ans = 1; else ans = list_search(search, list->next); } return ans; } This will make people cry as they try to work out how an answer appears from a d eep nested structure.

But both of these are great fun once you wrap your head around them. Until that point they are Hell.

You might also like