Rows & Rows of Structures

Remember that we can have arrays of anything. We even have arrays of arrays; that's how we get multi-dimensional arrays. Well, we can also have arrays of structures. This particular construct is much like we think of a table. Each row of the table represents some entity and each column is some attribute of the entities.

To be more concrete, let's return to our example of students. A table of students might look like:

Jim      Glassell-101      1234   99   3.59
Susan    Bellingrath-200   1235   99   3.61
Bill     New-300           2345   96   2.90
Christy  Robinson-300      2346   96   2.85
To store this information we can use the structure as we've used it before:
struct student {
   char name[30];
   char address[60];
   int extension;
   int grad_year;
   float gpa;
};

and we can declare a variable containing our student body:
struct student student_body[1500];

Remember that since student_body is an array of student structures, student_body[n] is a student structure for any integer value of n . (Values of n negative or greater than or equal to 1500 would be invalid and lead to unpredictable results.) So we could print out a list of students with a code fragment like


for(i = 0; i < num_stud; ++i)
   print_student(student_body[i]);

By way of another example, suppose we wanted a function that would look up a student and give us that student's index in the array. We could do it with this function:


int find_stud(char target[], struct student body[], int num_stud)
{
   int i;
   for(i = 0; i < num_stud && strcmp(target, body[i].name) != 0; ++i) ;
   if(i >= num_stud)
      return -1;
   else
      return i;
}

Read through this example carefully and make sure you understand what's going on here.
Write the for part of a loop (not the body) to step through the array of students backward. Use i for the loop variable.