twitter
    Find out what I'm doing, Follow Me :)

An Array Of Structures

Load and display the next program named struct2.c.

main( )
{
struct {
char initial;
int age;
int grade;
} kids[12];
int index;
for (index = 0;index < 12;index++) {
kids[index].initial = ’A’ + index;
kids[index].age = 16;
kids[index].grade = 84;
}
kids[3].age = kids[5].age = 17;
kids[2].grade = kids[6].grade = 92;
kids[4].grade = 57;
for (index = 0;index < 12;index++)
printf("%c is %d years old and got a grade of %d\n",
kids[index].initial,kids[index].age,
kids[index].grade);
}


This program contains the same structure definition as before but this time we define an array of 12 variables named "kids". This program therefore contains 12 times 3 = 36 simple variables, each of which can store one item of data provided that it is of the correct type. We also define a simple variable named "index" for use in the for loops.

In order to assign each of the fields a value, we use a for loop and each pass through the loop results in assigning a value to three of the fields. One pass through the loop assigns all of the values for one of the "kids". This would not be a very useful way to assign data in a real situation, but a loop could read the data in from a file and store it in the correct fields. You might consider this the crude beginning of a data base, which it is.

In the next few instructions of the program we assign new values to some of the fields to illustrate the method used to accomplish this. It should be self explanatory, so no additional comments will be given.