A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling. Structures help to organize complicated data, particularly in large programs, because they permit a group of related variables to be treated as a unit instead of as separate entities. Structure is a user defined data type, it permits logical grouping of related data (of different types) into a single type.
A structure is declared using the keyword struct, and the internal organization of the structure is defined by a set of variables enclosed in braces. For example, a person can have properties of name, age and gender. We could create a character array for name, an integer variable for roll and a character variable for gender. But if there are many person, it will be difficult to handle those variables.
We can declare a structure using the struct keyword following the syntax as below:
Syntax:
struct structureName
{ dataType memberVariable1;
datatype memberVariable2; … };
Example 1
Example 1
struct person {
char name[30];
int rollno;
char gender;
};
Explanation: The above statement defines a new data type struct person. Each variable of this data type will consist of name[30], rollno and gender. These are known as members of the structure. Once a structure is declared as a new data type, then the variables of that data type can be created.
Variable declaration:
Syntax:
struct structureName;
structureVariable;
Example 2
Example 2