In the previous chapters we had learned that how we can create the collection of different data having same data type. But what if we want to make collection of data of different data type. In this chapter we will learn about the structures which will help us to store data of different data types.

Array is used to store the data of same data types. Structure is similar to an array but structure is not only limited to store same data types, we can also store different data types in structure. It is a user-defined data type. It is used to represent the records.

Defining a Structure

While defining a structure we need to use struct statement.

Syntax of defining a structure
struct struct_name{
    member definition;
    member definition;
     ...
    member definition;
} [one or more structure objects];

Here struct_name is optional if you are providing structure object in definition. Also Structure objects are also optional if you provide struct_name you can create objects later where they are required.

Example
struct student{
    int rollno;
    char name[20];
    char address[30];
}s;

In the above example student is name of structure. And s is the structure object.

Accessing the structure members

To access the structure members we need a structure object. And We will use a member access operator (.) to access the structure members.

Program example of structure in C

//An example of structure in C
#include<stdio.h>
#include<string.h>

struct student{
    int rollno;
    char name[20];
    char address[30];
};

int main()
{
    struct student s;
    
    s.rollno = 12345;
    strcpy(s.name, "Richard");
    strcpy(s.address, "KTM");


    printf("Roll no of the student is = %d\n", s.rollno);
    printf("Name of the student is = %s\n", s.name);
    printf("Address of the student is = %s\n", s.address);
    return 0;
}

Output

Roll no of the student is = 12345
Name of the student is = Richard
Address of the student is = KTM