Handling Data Using Structures
Learn structures and their basic syntax with the help of an interactive example.
Introduction to structures
As we know, arrays do not permit the collection of dissimilar elements. To gather dissimilar elements together, we need to use a data type called structure.
Declaring a structure
The basic syntax for declaring a structure in C is given below:
The program given below declares a structure, employee, using a keyword called struct. The names, ages, and salaries are the members, or elements, of the structure, employee.
📝Note: A structure is usually a collection of dissimilar elements.
Creating a structure variable
After defining the structure, we can create a variable of its type using the following syntax:
struct structName structVariable;
Once the structure is declared, we have to create variables of its type. In our case, these variables are e1, e2, e3, and e4.
Assigning values to structure members
Method 1: assign a value to a single member
We can use the dot operator to access the particular member of the structure variable and assign it a value. . is known as a member access operator.
structureVariable . memberVariable = value;
The program given below assigns values to the members of e1 by using the dot operator.
Method 2: assign values to all members
Using the initializer list, we can assign values to all the structure members in one line.
structureVariable = { member1Value , member2Value ,.........., member(n)Value };
The program given below uses the initializer list to assign values to all the members of e1, e2, e3, and e4, respectively.
📝 Note: A structure is also known as a user-defined data type, an aggregate data type, a secondary data type, or a derived data type.