Array of Structures in C
An array of structures is an array where each element is a structure. It is one of the most common and powerful ways to store multiple records of the same type in C (like list of students, employees, books, products, etc.).
Think of it as a simple database table where each row is one structure and all rows have the same structure (same fields).
1. Declaring an Array of Structures
First define the structure, then create an array of that structure type.
C
#include <stdio.h>
#include <string.h>
struct Student {
char name[50];
int roll;
float marks;
};
int main() {
// Method 1: Declare array
struct Student class[5]; // array of 5 students
// Method 2: With size and initialization
struct Student top3[3] = {
{"Rahul", 101, 92.5},
{"Priya", 102, 95.8},
{"Aman", 103, 88.4}
};
return 0;
}
2. Accessing Elements of Array of Structures
You can access members using two ways:
array[index].member(array + index)->member(pointer style)
C
Access and print array of structures
for(int i = 0; i < 3; i++) {
printf("Student %d:\n", i+1);
printf("Name : %s\n", top3[i].name);
printf("Roll : %d\n", top3[i].roll);
printf("Marks: %.1f\n\n", top3[i].marks);
}
// Using pointer notation (same result)
// printf("%s\n", (top3 + i)->name);
3. Taking Input for Array of Structures
C
Reading data from user into array of structures
struct Student class[60];
int n;
printf("How many students? ");
scanf("%d", &n);
for(int i = 0; i < n; i++) {
printf("\nEnter details of student %d:\n", i+1);
printf("Name: ");
scanf(" %49[^\n]", class[i].name); // safe string input
printf("Roll: ");
scanf("%d", &class[i].roll);
printf("Marks: ");
scanf("%f", &class[i].marks);
}
4. Common Real-World Uses of Array of Structures
| Use Case | Structure Name | Typical Size |
|---|---|---|
| Student management system | Student | 30–200 |
| Employee database | Employee | 500–5000 |
| Book inventory | Book | 1000+ |
| Product catalog | Product | 200–10000 |
| Contact list / Phone book | Contact | 100–1000 |
| Transaction history | Transaction | 1000+ |
5. Passing Array of Structures to Function
You can pass array of structures to a function in two main ways:
- Pass whole array (decays to pointer)
- Pass individual structure (by value or pointer)
C
Passing array of structures to function
void printStudents(struct Student s[], int size) {
for(int i = 0; i < size; i++) {
printf("%-20s %4d %6.1f\n",
s[i].name, s[i].roll, s[i].marks);
}
}
// Call in main:
// printStudents(top3, 3);
Codecrown