Structure is a collection of variables referenced under a common name. Sometimes, some logically related elements need to be treated under one single unit. For instance, the elements that store student information (e.g., rollnumber, name, class, marks and grade) need to be processed together under one roof.

Defining a structure:

  • struct is a required keyword to define a structure.
  • tag-name is the name that identifies the structure.
  • member1, member2 and member3 are the members of the structure.

Complex data types can be constructed from fundamental data types.

Example:

oldcustomer and newcustomer are structure variables of type account.

Here, customer is a 100 element array of structures. Each element of customer is a separate structure of type account. Each customer includes all the members.

Variable declaration:

Structures can contain any C++ data type, including arrays, pointers or other structures.

Referencing Structure Elements

Once a structure has been defined, its members can be accessed with the use of dot (.) operator.

The structure variable name followed by a period (.) and the element name is the name of the specific structure variable.

Initialization of Structure

Structure elements can be initialized in 2 ways,

  1. By initializing every element individually
    oldcoustomer.name = ”Albert” ;
    oldcoustomer.accno = 372 ;
    oldcustomer.balance = 58880.50 ;
  2. By the notation which is used for the initialization of arrays

Nested Structure

A structure element may be either a complex or simple data-type. The simple data-type are any of the fundamental data-types such as int, char, float, double. However, a structure may have elements that are complex i.e. array, structure, etc. Thus, an element of a structure may even be an array or a structure itself. A structure which is a member of another structure, is known as nested structure.

Example:

Program 1:

Accepts data in the structure named student and display the contents.

Program 2:

Accepts data into an array of stuture and display the contents.

Output: