Arrays of Structures in C

Arrays of Structures in C


Introduction

In C programming, when we need to store multiple records of the same structure, we use arrays of structures.

👉 It helps manage large amounts of structured data efficiently.


What is an Array of Structures?

An array of structures is:
👉 A collection of structure variables stored in an array


Why Use Arrays of Structures?

  • ✔ Store multiple records
  • ✔ Easy data management
  • ✔ Used in real-world applications
  • ✔ Efficient memory usage

Syntax

struct structure_name array_name[size];

Example: Basic Array of Structures

#include <stdio.h>

struct Student {
int id;
float marks;
};

int main() {
struct Student s[2] = {
{1, 85.5},
{2, 90.0}
};

int i;

for (i = 0; i < 2; i++) {
printf("ID = %d, Marks = %.1f\n", s[i].id, s[i].marks);
}

return 0;
}

Output

ID = 1, Marks = 85.5
ID = 2, Marks = 90.0

Taking Input in Array of Structures

#include <stdio.h>

struct Student {
int id;
float marks;
};

int main() {
struct Student s[2];
int i;

for (i = 0; i < 2; i++) {
printf("Enter ID and Marks: ");
scanf("%d %f", &s[i].id, &s[i].marks);
}

for (i = 0; i < 2; i++) {
printf("ID = %d, Marks = %.1f\n", s[i].id, s[i].marks);
}

return 0;
}

Sample Output

Enter ID and Marks: 1 80.5
Enter ID and Marks: 2 90.0
ID = 1, Marks = 80.5
ID = 2, Marks = 90.0

Accessing Elements

👉 Use index + dot operator

s[0].id
s[1].marks

Array of Structures Using Pointer

#include <stdio.h>

struct Student {
int id;
};

int main() {
struct Student s[2] = {{1}, {2}};
struct Student *ptr = s;

printf("ID1 = %d\n", ptr->id);
printf("ID2 = %d\n", (ptr + 1)->id);

return 0;
}

Output

ID1 = 1
ID2 = 2

Advantages Table

Feature Benefit
Multiple Records Stores many data entries
Organization Structured data handling
Efficiency Better memory usage

Important Notes

  • Use index carefully
  • Use . for access
  • Use -> for pointer
  • Structure array works like normal array

Common Mistakes

  • ❌ Wrong indexing
  • ❌ Missing & in scanf
  • ❌ Confusing pointer access
  • ❌ Incorrect structure usage

Pro Tips

  • ✔ Use loops for structures
  • ✔ Combine with pointers
  • ✔ Practice input/output programs
  • ✔ Use meaningful structure names

Conclusion

Arrays of structures are very useful for storing multiple structured data efficiently. They are widely used in real-world applications.

Master this concept for advanced programming.

👉 This article is part of Dharani Tech Edu Hub — where learning programming is made simple and practical.

Comments

Popular posts from this blog

Introduction to C Programming

Operators in C

Input & Output in C