What is Difference Between Structure Pattern, Template and Variable in C Language

«
»
Question: What is Difference Between Structure Pattern, Template and Variable in C Language?

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’.

advertisement

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 = {&current, 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.

advertisement

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 = {&current, 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,

advertisement
    size = sizeof(Node);

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn