C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C programming language

Nested Structure with Example in C language

This article talks about one usage of structures in C. This will give a brief about a highly efficient way to use structures in C.

While structures in C contain homogeneous data types, they can also contain a structure(s) inside them. We can declare a structure inside a structure as shown below:

struct top{    
	int a;
	int b;
	struct inside_top object;
};

Above is the declaration for a structure which contains instance of another structure. Let's take the other structure's declaration like below and we will see then how can we use them.

struct inside_top{    
    int a;
};

An object created for the structure top will have access to all the members of the structure inside_top. Let’s see this with the help of a program. We will use the above two structures in this program.

int main()
{
    struct top ObjectOne;
    
    ObjectOne.a=101;
    ObjectOne.b=201;
    
    //below will show you how can we access the elements of inside_top
    ObjectOne.object.a=301;
    
    printf("%d\n%d\n%d\n",ObjectOne.a,ObjectOne.b,ObjectOne.object.a);

    return 0;
}

Output

101
201
301

What we see above is called Nesting of Structures or sometimes referred a Nested Structures. In a similar fashion we can also create structure which contains an instance of union inside it. The special properties of union make this combination very useful. Below is one such example:

#include <stdio.h>

struct Element{
    int a;
        union{
                char Vals[4];
                int AllVals;
            }ObjForVal;
}ObjForElement;

int main()
{
    char i;

    for(i=0;i<4;i++)
    {
        ObjForElement.ObjForVal.Vals[i]=0x50+i;
        printf("%x\n",ObjForElement.ObjForVal.Vals[i]);
    }

    //Now if one is aware of the feature of union they can use the below example
    printf("%x\n",ObjForElement.ObjForVal.AllVals);
    printf("%x\n %x\n",ObjForElement.ObjForVal.AllVals, ObjForElement.a );
    
    return 0;
}

Output

50
51
52
53
53525150
53525150
 0

This nesting can be of any size. With size I mean we can have a structure containing many structures. Applications where one needs to store multiple sets of values for one combination and yet having many such combinations. There can be any number of combinations created based on the usage in the application using structures and unions.







COMMENTS