đ§ĩ Array of Structures and Nested Structures in C
Structures in C allow grouping different data types into a single unit. When we use arrays with structures or place one structure inside another, we can model real-world data more effectively.
đš Array of Structures
We use an array of structures when we want to store multiple records of the same type.
✅ Example: Store information of 3 students
#include <stdio.h>
struct Student {
int id;
char name[50];
float marks;
};
int main() {
struct Student students[3];
for (int i = 0; i < 3; i++) {
printf("Enter info for student %d:\n", i + 1);
printf("ID: ");
scanf("%d", &students[i].id);
printf("Name: ");
scanf(" %[^\n]", students[i].name);
printf("Marks: ");
scanf("%f", &students[i].marks);
}
printf("\nStudent Records:\n");
for (int i = 0; i < 3; i++) {
printf("ID: %d, Name: %s, Marks: %.2f\n",
students[i].id, students[i].name, students[i].marks);
}
return 0;
}
Note: Use students[i].field
to access each member of the structure.
đš Nested Structures
A nested structure is a structure within another structure. It helps represent grouped sub-details (like address inside employee data).
✅ Example: Employee with Address
#include <stdio.h>
struct Address {
char city[30];
char state[30];
int zip;
};
struct Employee {
int id;
char name[50];
struct Address address;
};
int main() {
struct Employee emp;
printf("Enter Employee ID: ");
scanf("%d", &emp.id);
printf("Enter Name: ");
scanf(" %[^\n]", emp.name);
printf("Enter City: ");
scanf(" %[^\n]", emp.address.city);
printf("Enter State: ");
scanf(" %[^\n]", emp.address.state);
printf("Enter ZIP Code: ");
scanf("%d", &emp.address.zip);
printf("\nEmployee Information:\n");
printf("ID: %d\n", emp.id);
printf("Name: %s\n", emp.name);
printf("City: %s, State: %s, ZIP: %d\n",
emp.address.city, emp.address.state, emp.address.zip);
return 0;
}
Note: Access nested fields using emp.address.city
, emp.address.zip
, etc.
đ Summary Table
Concept | Syntax Example | Use Case |
---|---|---|
Array of Structures | struct Student students[100]; |
To manage a list of similar records |
Nested Structures | struct Employee { struct Address a; } |
To represent complex or grouped sub-data |
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ