Answer: Consider the declaration given below,
struct NODE { struct NODE *link; int value; };
The above declaration is called structure template or pattern. This declaration tells compiler, while compiling it, how to store members and makes the computer not to allocate any storage to it. This plays the same role as other types as ‘int’, ‘char’, ‘float’, ‘double’ etc. Here, new type created is ‘struct NODE’.
We know how can we declare and initialize variables of any type, for example,
int junks = 10; char colour[10] = {'y','e','l','l','o','w'}; float avg;
Likewise, we, firstly, try to create variables of type ‘struct NODE’,
struct NODE current; struct NODE next = {¤t, 100}; /* next declared and initialized */
Since, ‘next’, a variable of ‘struct NODE’, contains two members viz. ‘link’, a pointer to a variable of type ‘struct NODE’ and an integer. We initialized ‘link’ with address of ‘current’, a variable of ‘struct NODE’ and value as 100.
Since, ‘link’, a member of ‘next’, is a ‘pointer-to-struct NODE’. Such structures are called self-referential structures.
We can use ‘typedef’ keyword to give structure template ‘struct NODE’ a new type name of ours’ choice. Let’s try this, now,
typedef struct NODE { struct NODE *link; int value; } Node;
‘Node’ is created a new type. Now we rewrite the above declarations using ‘Node’ type as,
int main(void) { Node current; Node next = {¤t, 100}; }
Notice also that each type, say ‘int’, ‘char’ or ‘float’ or some other, specifies amount of storage compiler allocates to their variables on a particular machine. Likewise, type ‘Node’ or ‘struct NODE’ specifies amount of storage to its variables on Linux. Use sizeof operator to evaluate size, in bytes, of any variable of type ‘Node’. For example,
size = sizeof(Node);
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Check C Books
- Practice BCA MCQs
- Watch Advanced C Programming Videos
- Practice Computer Science MCQs
- Check Computer Science Books