C

How to create a sub structure in C Programming2 min read

In C, structures can be nested. A structure can be defined within in another structure. The members of the inner structure can be accessed using the variable of the outer structure as shown below:

outer–struct–variable.inner–struct–variable.membername




An example for a nested structure is shown below:

In the above example, student is the outer structure and the inner structure name consists of three members: fname, mname and lname.

Structures and Functions

We know that the functions are the basic building blocks of a C program. So, it is natural for C language to support passing structures as parameters in functions. We pass a copy of the entire structure to the called function. Since the function is working on a copy of the structure, any changes to structure members within the function are not reflected in the original structure. The syntax for passing the structure variable as a parameter is shown below:

We can access and assign values to the members of a structure in a number of ways. As mentioned earlier, the members themselves are not variables. They should be linked to the structure variables in order to make them meaningful members. The link between a member and a variable is established using the member operator ‘ . ‘ which is also known as dot operator or period operator. The syntax for accessing a structure member is as shown below:

structure–varaible.membername

Examples of accessing the members of the student structure are shown below:

Structure Initialization

Like any other data type, a structure variable can be initialized at compile time. An example of compile time initialization of the student structure is shown below:

In the above example: teja, 10A1, 26 and A are assigned to student1’s name, rollno, age and grade. Whereas raju, 10A2, 24, B are assigned to student2’s name, rollno, age and grade.

Note: Partial initialization of a structure variable is supported. For example we can assign values to name and rollno and leave out age and grade. In case of partial initialization, the default values for int type is zero. For float and double it is 0.0. For characters and strings it is ‘\0’.

An example for dynamic initialization is shown below:

Take your time to comment on this article.

Leave a Comment