Structure

0 wilfredohumpher November 25, 2020

A structure is a collection of variables under a single name. These variables can be of different types, and each has a name that is used to select it from the structure. The variables are called members of the structure. A structure is a convenient way of grouping general pieces of the related information together.

A structure can be defined as a new named type or user-defined data type, thus extending the number of available types. It can be our other structures, arrays, or pointers as some of its members.

Defining a Structure

The syntax od structure is

struct structure_name
{
    data_type member_variables1;
    data_type member_variables2;
    ...... .......
    data_type member_variablesn;
}

Once structure_name is declared as a new data type, the variable of that can be declared as 

struct structure_name structure_variable;

Let’s take an example to make clear concepts on a structure.

#include <stdio.h>

// Here we have created structure as `StudentData`
struct StudentData{
    char *stu_name;
    int stu_id;
    int stu_age;
};

int main()
{
     /* Here we have declared variable of structure as `student`*/
     struct StudentData student;

     /*Assign the value in each member of structure*/
     student.stu_name = "Steve";
     student.stu_id = 1234;
     student.stu_age = 30;

     /* displaying the each member of structure */
     printf("The Student Name is: %s", student.stu_name);
     printf("\nThe Student Id is: %d", student.stu_id);
     printf("\nThe Student Age is: %d", student.stu_age);
     return 0;
}

The output of the above program is:

The Student Name is: Suresh
The Student Id is: 987
The Student Age is: 21