What are type defined structures in C Programming3 min read

We can use the keyword typedef to define a structure as follows:

The name student represents the structure definition associated with it and therefore can be used to declare structure variables as shown below:

Accessing Structure Members

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:

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:

Arrays of Structures

We use structures to describe the format of a number of related variables. For example, we want to store details of 100 textbooks it will become difficult to declare and maintain 100 variables and store the data. Instead, we can declare and array of structure variables as shown below:

In the above example, we are declaring an array book with 10 elements of the type textbook which is a structure.

Structures within Structure

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:

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:

Take your time to comment on this article.

Leave a Comment