Structures . Structures Introduction Structure is a user-defined which has the combination of data items with different data types. This allows to group variables of mixed data types together into a single unit. .
. Purpose of Structures In any situation when more than one variable is required to represent objects of uniform data-types, array can be used. If the elements are of different data types,then array cannot support. If more than one variable is used, they can be stored in memory but not in adjacent locations.
It increases the time consumption while searching. The structure provides a facility to store different data types as a part of the same logical element in one memory chunk adjacent to each other. . .
Declaring and defining structures Structure is declared using the keyword ‘struct’. The syntax of creating a structure is given below. struct { type ; type ; Objects declared along with structure definition are called global objects } ; An optional field can be used to declare objects of the structure type directly. Example: struct Student long rollno; int age; float weight; } ; In the above declaration of the struct, three variables rollno,age and weight are used.
These variables(data element)within the structure are called members (or fields). In order to use the Student structure, a variable of type Student is declared and the memory allocation is shown in figure . Chapter Page - - Rollno Age weight Bytes Bytes Bytes Fig . Memory Allocation struct Student balu; // create a Student structure for Balu This defines a variable of type Student named as Balu.
Similar to normal variables, struct variable allocates memory for that variable itself. It is possible to define multiple variables of the same struct type: struct Student frank; // create a structure for Student Frank. For example, the structure objects balu and frank can also be declared as the structure data type as: struct Student longrollno; int age; float weight; } balu, frank; . .
Referencing Structure Elements Once the two objects of student structure type are declared (balu