A structure is custom or user define data type which can have multiple fields with different data type. C also allows to create array of structure similar to other data type by using square braces and specifying size of array.
An array of structure can be define either globally or local based on the requirement. The global structure variable is accessible in entire program while local structure variable is only accessible only in the function where it define.
Array of structure in C language
1 #include <stdio.h>
2
3 struct Emp {
4 int id;
5 char *name;
6 float salary;
7 }emp[2];
8
9 int main() {
10
11 int i;
12 emp[0].id = 10;
13 emp[0].name = "First";
14 emp[0].salary = 10000;
15
16 emp[1].id = 20;
17 emp[1].name = "Second";
18 emp[1].salary = 20000;
19
20
21 for(i=0; i<2; i++) {
22 printf("Employee Id : %d", emp[i].id);
23 printf("\nEmployee name : %s", emp[i].name);
24 printf("\nEmployee salary : %.2f", emp[i].salary);
25 printf("\n");
26 }
27
28 return 0;
29 }
In the above example, An array of structure is define as global variable which is accessible in the entire program but if you want to define array of structure as local variable, similar to local structure variable.
1 Employee Id : 10
2 Employee name : First
3 Employee salary : 10000.00
4 Employee Id : 20
5 Employee name : Second
6 Employee salary : 20000.00
Read array of structure from user
Read array of structure from user
1 #include <stdio.h>
2
3 struct Emp {
4 int id;
5 char name[20];
6 float salary;
7 }emp[2];
8
9 int main() {
10 int i = 0;
11
12 for(i = 0; i < 2; i++) {
13 printf("Enter employee id : ");
14 scanf("%d", &emp[i].id);
15 printf("Enter employee name : ");
16 scanf("%s", &emp[i].name);
17 printf("Enter employee salary : ");
18 scanf("%f", &emp[i].salary);
19 }
20 printf("Employee details :\n");
21 for(i = 0; i < 2; i++) {
22 printf("%d, %s, %.2f", emp[i].id, emp[i].name, emp[i].salary);
23 printf("\n");
24 }
25 return 0;
26 }
In the above example, a structure array is define as global variable and reading value from user by specifying inside for loop. It reads value and assigned to the structure array elements using index position. A array are iterated using for loop and print structure member using index position.
1 Enter employee id : 101
2 Enter employee name : emp1
3 Enter employee salary : 10000
4 Enter employee id : 202
5 Enter employee name : emp2
6 Enter employee salary : 20000
7
8 Employee details :
9 101, emp1, 10000.00
10 202, emp2, 20000.00
Related options for your search