Nearby lessons

60 of 72

C - Array of Structures

An array of structures stores multiple records of the same structure type. For example, we can store details of many students in one array.

1. Create an Array of Structures

First, define the structure. Then create an array using the structure type. In this example, students[0] is the first student and students[1] is the second student.

Example01
CCode Cell
1#include <stdio.h>
2 
3struct Student {
4 int rollNo;
5 char name[30];
6 float marks;
7};
8 
9int main(void) {
10 struct Student students[3] = {
11 {101, "Rahul", 88.5f},
12 {102, "Priya", 92.0f},
13 {103, "Amit", 79.5f}
14 };
15 
16 printf("%s\n", students[0].name);
17 printf("%d\n", students[1].rollNo);
18 printf("%.1f\n", students[2].marks);
19 
20 return 0;
21}
Output
Rahul
102
79.5

2. Display All Students Using a Loop

Use a for loop to visit each array element. Use students[i].memberName to access a member of the current student.

Example02
CCode Cell
1#include <stdio.h>
2 
3struct Student {
4 int rollNo;
5 char name[30];
6 float marks;
7};
8 
9int main(void) {
10 struct Student students[3] = {
11 {101, "Rahul", 88.5f},
12 {102, "Priya", 92.0f},
13 {103, "Amit", 79.5f}
14 };
15 int i;
16 
17 for (i = 0; i < 3; i++) {
18 printf("Roll: %d, Name: %s, Marks: %.1f\n",
19 students[i].rollNo,
20 students[i].name,
21 students[i].marks);
22 }
23 
24 return 0;
25}
Output
Roll: 101, Name: Rahul, Marks: 88.5
Roll: 102, Name: Priya, Marks: 92.0
Roll: 103, Name: Amit, Marks: 79.5

3. Remember the Syntax

  • students[0] selects the first structure variable.
  • students[0].name accesses the first student's name.
  • Array indexing starts from 0, so an array of three records uses indexes 0, 1, and 2.

Common Mistakes

  • Do not start the loop at index 1 if you want to include the first record.
  • Do not use an index equal to the array length; for three records, valid indexes are 0 to 2.
  • Use both the index and dot operator, such as students[i].marks.
📝 Key Takeaways
  • An array of structures stores multiple records.
  • Each array element is one complete structure variable.
  • Use an index to select a record and the dot operator to access its members.
  • A loop can display all records without repeating the same code.

🧠 Test Your Knowledge

2 Questions
Progress: 0 / 2