Array of Structure
An array of structures is simply an array where each element is a structure. It allows you to
store several structures of the same type in a single array.
Structure Declaration:
struct struct_name arr_name [size];
Initialization:
A structure can be initialized using initializer list and so can be the array. Therefore, we can
initialize the array of structures using nested initializer list.
#include <stdio.h>
#include <string.h>
// Structure definition
struct A
{
int var;
char c;
};
int main()
{
// Declaration and initialization using nested initializer list
struct A arr1[2] = { {1, 'a'}, {2, 'b'} };
// Declaration and initialization using non-nested initializer list
struct A arr2[2] = { 10, 'A', 20, 'B' };
for (int i = 0; i < 2; i++)
printf("%d %c", arr1[i].var, arr1[i].c);
printf(" ");
for (int i = 0; i < 2; i++)
printf("%d %c", arr2[i].var, arr2[i].c);
printf("");
return 0;
}
Access and Update Members:
To access the members of a structure in an array, use the index of the array element followed
by the dot (.) operator.
The general syntax is:
arr_name[index].member_name
where,
arr_name: The name of the array of structures.
index: The index of the structure element in the array.
member_name: The member within the structure you want to access.
#include <stdio.h>
#include <string.h>
// Structure definition
struct A {
int var;
char c;
};
int main() {
struct A arr[2] = { {1, 'a'}, {2, 'b'} };
// Access the member c of second element of arr
printf("%c",arr[1].c);
// Update the value and access again
arr[1].c = 'Z';
printf("%c",arr[1].c);
return 0;
}
Structure within Structure / Nested Structure
A nested structure in C is a structure within a structure. One structure can be declared inside
another structure in the same way structure members are declared inside a structure.
Creating Nested Strucutres :
A nested structure allows the creation of complex data types according to the requirements
of the program.
Syntax:
struct name_1 {
member1;
member2;
.....
.....
membern;
struct name_2 {
member_1;
member_2;
.....
.....
member_n;
}, var1
} var2;
The members of a nested structure can be accessed using the following syntax:
Outer_Structure.Nested_Structure.data member
EXAMPLE:
#include <stdio.h>
#include <string.h>
struct employee
{
char name[10];
float salary;
struct dob
int d, m, y;
d1;
};
int main()
struct employee e1 = {"Kiran", 25000, {12, 5, 1990}};
printf("Name: %s\n", [Link]);
printf("Salary: %f\n", [Link]);
printf("Date of Birth: %d-%d-%d\n", e1.d1.d, e1.d1.m, e1.d1.y);
return 0;