C Array Of Structures

Let's explore a demonstration showcasing an array of structures that holds details concerning 5 students and then displays this information.

Example

Example

#include<stdio.h>

#include <string.h>  

struct student{  

int rollno;  

char name[10];  

};  

int main(){  

int i;  

struct student st[5];  

printf("Enter Records of 5 students");  

for(i=0;i<5;i++){  

printf("\nEnter Rollno:");  

scanf("%d",&st[i].rollno);  

printf("\nEnter Name:");  

scanf("%s",&st[i].name);  

}  

printf("\nStudent Information List:");  

for(i=0;i<5;i++){  

printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);  

}  

   return 0;  

}

Output:

Output

Enter Records of 5 students

Enter Rollno: 1

Enter Name: John

Enter Rollno: 2

Enter Name: Michael

Enter Rollno: 3

Enter Name: Ronaldo

Enter Rollno: 4

Enter Name: Anthony 

Enter Rollno: 5

Enter Name: Mathew



Student Information List: 

Rollno: 1, Name: John

Rollno: 2, Name: Michael

Rollno: 3, Name: Ronaldo

Rollno: 4, Name: Anthony

Rollno: 5, Name: Mathew

Explanation:

In this illustration, we declare a structure named student with two components: rollno and name. Through an iterative process, it gathers and retains the roll number and name information for 5 students, subsequently exhibiting the recorded student details. The user input is acquired via scanf, and the information is showcased in an organized layout through printf.

Array of Structure Declaration

After establishing the format, an array of structures can be defined in the same manner as any other variable.

struct structname arrayname [Size]

In this declaration,

  • struct_name: It represents the name of the structure type that must be defined earlier.
  • array_name: It represents the name of the array that will hold multiple structure variables.
  • [Size]: It represents the number of elements that the array can hold.
  • Basic Operations on an Array of Structures

There exist various fundamental operations that can be performed on an array of structures in the C programming language. A few of these operations include:

Initialization of Struct Array

In the C programming language, it's possible to set initial values for both structures and arrays using an initializer list. This allows for the utilization of a nested initializer list to initialize an array of structures.

Syntax:

It has the following syntax:

Example

struct struct_name array_name [Size] = {

                {element1_num1, element1_num2, ....},

                {element2_num1, element2_num2, ....},

                 ......

                 ......

};

Here is an example demonstrating the initialization of an array of structures in C:

Example

#include <stdio.h>

// Define a structure
struct Person {
    char name[50];
    int age;
};

int main() {
    // Initialize an array of structures
    struct Person people[3] = {
        {"Alice", 25},
        {"Bob", 30},
        {"Charlie", 22}
    };

    // Access and print the values
    for(int i = 0; i < 3; i++) {
        printf("Person %d: %s is %d years old\n", i+1, people[i].name, people[i].age);
    }

    return 0;
}

In this example, a structure Person with fields name and age is defined. An array people of Person structures is then initialized with three elements, each containing a name and an age. Finally, a loop is used to access and print the values of each structure in the array.

Let's consider an example to demonstrate how we can set up an array of structures.

Example

Example

#include <stdio.h>

strucLogic Practice {

    float x;

    float y;

};

int main() {   //main function

    struct PoinLogic Practices1[2] = { {1.2, 2.6}, {3.32, 4.6} };

    struct PoinLogic Practices2[2] = { 5.8, 6.4, 7.2, 8.9 };

    struct PoinLogic Practices3[2] = { {.x = 9.26, .y = 10.9},

                                {.y = 12.45, .x = 11.3} };

    printf("Points1:\n");

    for (int i = 0; i < 2; i++)

        printf("(%.1f, %.1f)\n", points1[i].x, points1[i].y);

    printf("\nPoints2:\n");

    for (int i = 0; i < 2; i++)

        printf("(%.1f, %.1f)\n", points2[i].x, points2[i].y);

    printf("\nPoints3:\n");

    for (int i = 0; i < 2; i++)

        printf("(%.1f, %.1f)\n", points3[i].x, points3[i].y);

    return 0;

}

Output:

Output

Points1:

(1.2, 2.6)

(3.3, 4.6)



Points2:

(5.8, 6.4)

(7.2, 8.9)



Points3:

(9.3, 10.9)

(11.3, 12.4)

Explanation:

In this example, we have taken a Point struct with two members of type float: x and y. After that, it declares three arrays of the struct (points1, points2, points3) and initializes them in different ways by using nested braces, flat (not nested) values, and designated initializers. Finally, it prints the coordinates from all three arrays through a loop. The output displays the (x, y) values of all points in each array.

Access and Update Members

When accessing the components of a structure within an array, we need to utilize the array index along with the dot (.) operator.

Syntax:

It has the following syntax:

Example

array_name[ind].mem_name

In this syntax,

  • array_name: It represents the array of structures name.
  • ind: It represents the structure element index in the array.
  • mem_name: It represents the member of the structure that we want to access.

Access and Update Members Example

Let's consider an access example to demonstrate how to retrieve and modify members in C.

Example

Example

#include <stdio.h>

struct Car {

    char model[20];

    int year;

};

int main() {    //main function

    struct Car cars[2] = {

        {"Honda", 2015},

        {"Toyota", 2018}

    };

    

    cars[0].year = 2020;

    cars[1].year = 2022;

    printf("After Update:\n");

    for (int i = 0; i < 2; i++) {

        printf("Model: %s, Year: %d\n", cars[i].model, cars[i].year);

    }

    return 0;

}

Output:

Output

After Update:

Model: Honda, Year: 2020

Model: Toyota, Year: 2022

Explanation:

In this illustration, we create a class named Car containing a model (string) and year (integer). We instantiate an array of cars with two entries. Subsequently, we update the year values of both cars by directly accessing them through array indices (cars[0].year, cars[1].year). Lastly, the for loops iterate through the array and display the updated model and year for each car.

Traversing of Array of Structure

In C programming language, navigating through a structured array is straightforward. It enables us to iterate over every element of the array structure in a specific order. When traversing arrays in C, loops are employed to retrieve each element of the array.

C Example for Traversing of Array Structure

Let's consider a scenario to demonstrate the process of navigating through an array structure in the C programming language.

Example

Example

#include <stdio.h>

struct Employee {

    int id;

    char name[30];

    float salary;

};

int main() {    //main function

    struct Employee emp[3] = {

        {1, "John", 50000},

        {2, "Michael", 55000},

        {3, "Anthony", 60000}

    };

    printf("Employee Details:\n");

    for (int i = 0; i < 3; i++) {

        printf("ID: %d\n", emp[i].id);

        printf("Name: %s\n", emp[i].name);

        printf("Salary: %.2f\n\n", emp[i].salary);

    }

    return 0;

}

Output:

Output

Employee Details:

ID: 1

Name: John

Salary: 50000.00



ID: 2

Name: Michael

Salary: 55000.00



ID: 3

Name: Anthony

Salary: 60000.00

Explanation

In this instance, we define a structure named Employee to store details such as the employee's identification number, name, and wage. We initialize an array called emp with three records of employees. Within the main function, it loops through each item in the array using a for loop and displays the ID, name, and wage of each employee by utilizing the printf function.

Find the Size of an Array of Structures

In C programming, the size of an array of structures can be determined by either the size of the structure itself or by the number of elements in the array.

Here is an example in C to determine the size of an array of structures:

Example

#include <stdio.h>

struct Person {
    char name[50];
    int age;
};

int main() {
    struct Person people[5];
    int size = sizeof(people) / sizeof(people[0]);

    printf("The size of the array of structures is: %d\n", size);

    return 0;
}

Let's consider a scenario to demonstrate the process of determining the size of an array of structures.

Example

Example

#include <stdio.h>

struct Student {

    int roll;

    char name[30];

};

int main() {   //main function

    struct Student students[] = {

        {1, "vineeth"},

        {2, "suma"},

        {3, "William"},

        {4, "James"}

    };

    int totalSize = sizeof(students);                  

    int singleSize = sizeof(struct Student);           

    int count = totalSize / singleSize;    

    printf("Total students: %d\n", count);

    return 0;

}

Output:

Output

Total students: 4

Explanation:

In this instance, we define a structure named Student and initialize an array holding four student entries. The overall size of the array is determined using sizeof(students), while the size of an individual structure is calculated using sizeof(struct Student). Dividing the total size by the size of a single element yields the number of students, which is then displayed.

Declaring a Pointer to an Array of Structs

In the C programming language, it is also possible to declare a pointer to an array of structures. C utilizes the pointer operator to access the individual members of struct variables.

In this C example, we demonstrate how to declare a pointer to an array of structures.

Example

include<stdio.h>

include <string.h>

struct student{

int rollno;

char name[10];

};

int main{

int i;

struct student st[5];

printf("Enter Records of 5 students");

for(i=0;i<5;i++){

printf("\nEnter Rollno:");

scanf("%d",&st[i].rollno);

printf("\nEnter Name:");

scanf("%s",&st[i].name);

}

printf("\nStudent Information List:");

for(i=0;i<5;i++){

printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);

}

return 0;

}

Example

    char name[50];
    int age;
};

int main() {

Enter Records of 5 students

Enter Rollno: 1

Enter Name: John

Enter Rollno: 2

Enter Name: Michael

Enter Rollno: 3

Enter Name: Ronaldo

Enter Rollno: 4

Enter Name: Anthony

Enter Rollno: 5

Enter Name: Mathew

Student Information List:

Rollno: 1, Name: John

Rollno: 2, Name: Michael

Rollno: 3, Name: Ronaldo

Rollno: 4, Name: Anthony

Rollno: 5, Name: Mathew

Example

    struct Person (*ptr)[3] = &people;

    return 0;
}

Let's consider an example to demonstrate the process of declaring a pointer to an array of structures in the C programming language.

Example

Example

#include <stdio.h>

struct Student {

    int id;

    char name[20];

};

int main() {   //main function

    struct Student students[3] = {

        {1, "James"},

        {2, "Harry"},

        {3, "Thomas"}

    };

    struct Student *ptr = students;

    for (int i = 0; i < 3; i++) {

        printf("ID: %d, Name: %s\n", (ptr + i)->id, (ptr + i)->name);

    }

    return 0;

}

Output:

Output

ID: 1, Name: James

ID: 2, Name: Harry

ID: 3, Name: Thomas

Explanation:

In this instance, a Student structure was utilized to form an array consisting of three instances of 'Student' objects. Following this, a pointer was employed to reference the base location of the array, executing pointer calculations through the arrow (->) operator to retrieve and display the ID and name details of each student.

Advantages of an Array of Structures

There are several advantages of an array of structures in C. Some of them are as follows:

  • Efficient Organization of Data: It helps to gather related attributes into one structure and organizes them as a collection of similar records easily.
  • Convenience in Access: It provides indexed access to individual records, which makes it easy to retrieve and manipulate data.
  • Scalability: It allows manipulation of large volumes of data, like thousands of records, through one manageable array.
  • Flexibility: It allows homogeneous collections of records to be created, thereby facilitating operations such as sorting or searching.
  • Code Readability: It eliminates clutter through logical organization of data, enhancing program structure and maintenance.
  • Need for an Array of Structures

In most real-world usages, applications tend to handle a set of related but separate records, such as employee information, student grades, or product catalogues. An array of structures serves the purpose by offering:

  • Uniform Representation: It guarantees that all the records have the same attributes and structure.
  • Simplified Data Management: It facilitates managing big data by bringing multiple single records together into one single, structured entity.
  • Logical Grouping: Consolidates attributes per record, which reduces redundancy and errors compared to dealing with different arrays for each attribute.
  • Real-world Applications: It is mainly suited for applications such as building databases, applying algorithms that manipulate structured data, or constructing user-defined types of data.
  • Conclusion

In summary, arrays of structures in C offer a sturdy and organized method for handling collections of interconnected data elements, like students, employees, or products. By combining the benefits of arrays and structures, this approach allows developers to efficiently manage, access, modify, and analyze data for various instances of a particular category.

It enables improved code legibility, expandability, and manageability, especially in software that deals with organized data in large quantities. Proficiency in handling arrays of structures is essential for developing well-structured, resilient C programs that efficiently manage practical data scenarios.

C Array of Structures FAQs

1) What is an array of structures in C?

An array of structures is a collection of structure instances where each element holds data of identical type but represents distinct entities, like various students, vehicles, or films.

Using an array of structures is preferred over individual structure variables for several reasons:

  • ```

struct structname arrayname [Size] = {

{element1num1, element1num2, ....},

{element2num1, element2num2, ....},

......

......

};

Example

- It simplifies our code by enabling us to access and manipulate the data using loops and indexing.
- ```
struct struct_name array_name [Size] = {

                {element1_num1, element1_num2, ....},

                {element2_num1, element2_num2, ....},

                 ......

                 ......

};
  • It promotes code reusability as the same operations can be performed on each element of the array.
  • Overall, using an array of structures enhances the scalability and maintainability of our programs.

In C, managing an array of structures with individual variables for each structure (such as s1, s2, s3, etc.) can be cumbersome and inefficient, especially when dealing with extensive datasets. Utilizing an array of structures offers a more sophisticated and adaptable approach.

Yes, it is possible to initialize an array of structures when it is declared in C.

Yes, Nested initializer lists or designated initializers can be employed.

For Example:

Example

struct PoinLogic Practices[2] = { {1.2, 2.6}, {3.3, 4.6} };

4) What is the method for accessing or modifying structure elements in an array?

To modify or retrieve the structure elements, we can employ the dot operator and index in the C programming language.

Example

array_name[index].member = value;

5) Is it possible to utilize pointers with an array of structures in the C programming language?

Yes, set a pointer to the array's starting point and utilize pointer arithmetic with the -> operator to reach elements.

Input Required

This code uses input(). Please provide values below: