A structure is a user defined data type. We know that arrays can be used to represent a group of data items that belong to the same type, such as int or float. However we cannot use an array if we want to represent a collection of data items of different types using a single name. A structure is a convenient tool for handling a group of logically related data items.
The syntax of structure declaration is
type element 1; type element 2; …………….. type element n;
In structure declaration the keyword struct appears first, this followed by structure name. The member of structure should be enclosed between a pair of braces and it defines one by one each ending with a semicolon. It can also be array of structure. There is an enclosing brace at the end of declaration and it end with a semicolon.
We can declare structure variables as follows
struct structure_name var1,var2,…..,var n;
For Example: To store the names, roll number and total mark of a student
you can declare 3 variables. To store this data for more than one student 3 separate arrays may be declared. Another choice is to make a structure. No memory is allocated when a structure is declared. It just defines the “form” of the structure. When a variable is made then memory is allocated. This is equivalent to saying that there's no memory for “int” , but when we declare an integer that is. int var; only then memory is allocated. The structure for the above-mentioned case will look like
We can now declare structure variables stud1, stud2 as follows struct student stud1,stud2; Thus, the stud1 and stud2 are structure variables of type student. The above structure can hold information of 2 students. It is possible to combine the declaration of structure combination with that of the structure variables, as shown below.
type element 1;
type element 2;
type element n;
The following single declaration is equivalent to the two declaration presented in the previous example.
} stud1, stud2;
The different variable types stored in a structure are called its members. The structure member can be accessed by using a dot (.) operator, so the dot operator is known as structure member operator.
Example: In the above example stud1 is a structure variable of type student. To access the member name, we would write stud1.name Similarly, stud1’s rollno and stud1’s totalmark can be accessed by writing stud1.rollno And stud1.totalmark