Uncategorized

Structures

Structures:

We have seen how ordinary variables can hold one piece of information and how arrays can hold a number of pieces of information of the same data type. These two data types can be useful in different ways, but sometimes we come across situations where we need to store multiple entries but of dissimilar data types. For example you need to store information of an employee then I need to store;

  • His name (string)
  • Age (unsigned integer)
  • Phone number (integer)
  • Address (string)

For this case, we can follow two approaches;

  1. Construct individual arrays for each data type.
  2. Use a structure variable.

There is no problem in writing a program with individual arrays, but it require more code to be written. C provides an efficient data structure for these cases that is structure.

Structure contains a number of data types grouped together. You can make this combination of data types yourself. Means Structures are more like user defined data types.

Defining a Structure:

The key word “struct” is used to define a structure. Then the name of the Structure defined by user. Variable of different data types are declared in the curly brackets, and the closing curly bracket must be followed by semicolon.

Syntax:

Example:

Here, the name of structure is Student, which has four elements or members, namely name, age, branch and gender.

Each member is of different data type. Like in this example name is a string, age is integer, branch is a string and gender is a character.

Declaring Structure Variable:

Once you define the structure, you can now create variables of that structure type. There are two ways of doing this;

  1. Declaring structure variable separately:
  1. Declaring structure variable with structure definition:

This approach is possible but not recommended.

Accessing Structure Members:

Structure members can be accessed using a “.” Operator, this operator is called period or member access operator. The operator is used to link the variable with the structure in order to access the variable because structure variables have no meaning without the structure.

Example;

Output of the above code will be;

Name of Student 1: Jhon

Age of Student 1: 18

Structure Initialization:

Like other variables, structure type variables can also be initialized.

OR