Array of Structures in C

Array of structures in c programming; In this tutorial, i will show you how to create and use array of structures in c programming.

Array of Structures in C

Here, i will show you how to create and use array of structures in c programming:

  • What is Array of Structures in C
  • Define Array of structures in C
  • C Program using Array of Structures

What is Array of Structures in C

An array of structures in C can be represented as the collection of different datatype structures variables, where each variable contains information about multiple entities of different data types. And the array of structures is also known as the collection of structures.

Define Array of structures in C

The following code declares a structure to store student details. Along with the structure declaration, it declares an array of structure objects to store 100 student details; as shown below:

// Array of structure declaration along with structure 
struct student 
{
    char  name[100];
    int   roll;
    float marks;
} stu[100];

C Program using Array of Structures

See the following c program using array of structures; as shown below:

/**
 * How to declare, initialize and access array of structures in C
 */
#include 
#define MAX_STUDENTS 5
// Student structure type declaration
struct student 
{
    char    name[100];
    int     roll;
    float   marks;
};
int main()
{
    // Declare array of structure variables
    struct student stu[MAX_STUDENTS];
    int i;
    // Read all 5 student details from user
    printf("Enter %d student details\n", MAX_STUDENTS);
    for ( i = 0; i < MAX_STUDENTS; i++ )
    {
        printf("Student %d name: ", (i + 1));
        gets(stu[i].name);
        printf("Student %d roll no: ", (i + 1));
        scanf("%d", &stu[i].roll);
        printf("Student %d marks: ", (i + 1));
        scanf("%f", &stu[i].marks);
        getchar();  // <-- Eat extra new line character
        printf("\n");
    }
    
    // Print all student details
    printf("\n\nStudent details\n");
    printf("---------------------------\n");
    for ( i = 0; i < MAX_STUDENTS; i++ )
    {
        printf("Name : %s\n",   stu[i].name);
        printf("Roll : %d\n",   stu[i].roll);
        printf("Marks: %.2f\n", stu[i].marks);
        printf("---------------------------\n");
    }
    return 0;
}

In the above c program example of an array of structures that holds information of 5 students and prints it.

Be First to Comment

Leave a Reply

Your email address will not be published.