------------------------------------------------------------ Pointers and Arrays of Structures Consider these declarations again: typedef struct { char name[30]; int score; char grade; } Student; int main (void) { Student student1, student2; Student students[100]; Student *stp, *stp2; Consider the following loop: 1 stp = students; /* stp points to 1st struct in array */ 2 for (i = 0; i < 100; i++) { 3 stp->score = 0; 4 stp->grade = 'A'; 5 strcpy(stp->name,"unknown"); 6 stp++; 6 } Things to notice: * line 6: when we increment stp, we are not adding just "1" to the address. Instead, we are adding the size of a Student structure (e.g., let's say it takes up 32 elements). The key point: if a pointer points to one structure in an array, and we increment that pointer, it then points to the next structure in the array. How convenient! Thus, as programmers, we don't have to keep track of things like how big the Student structure is. We just add 1 in our statement, and know that the C compiler will change the address appropriately. Just as an aside: Here is one more equivalent loop: 1 stp = students; /* stp points to 1st struct in array */ 2 for (i = 0; i < 100; i++) { 3 *(stp+i).score = 0; 4 *(stp+i).grade = 'A'; 5 strcpy( *(stp+i).name, "unknown"); 6 } The previous loop is better, though; *much* easier to read. ------------------------------------------------------------ Functions and Structures Let's write a function "init" to do the same thing as the loop above: #include typedef struct { char name[30]; int score; char grade; } Student; void init(Student list[], int n); int main(void) { Student student1, student2; Student students[100]; Student *stp, *stp2; init(students,100); return(0); } void init(Student list[], int n) { int i; for (i = 0; i < n; i++) { list[i].score = 0; list[i].grade = 'A'; strcpy(list[i].name,"unknown"); } } Very similar to a function that works on an array of a "regular" data type like "int". Now let's look at a variation. Below, the init function initializes just 1 structure, and we call init 100 times from main to initialize the whole array. #include typedef struct { char name[30]; int score; char grade; } Student; void init(Student *p, int n); int main(void) { Student student1, student2; Student students[100]; Student *stp, *stp2; int i; for (i = 0; i < 100; i++) init(&students[i]); /* equivalently: init(students+i) */ return(0); } void init(Student *p) { p->score = 0; p->grade = 'A'; strcpy(p->name,"unknown"); } ------------------------------------------------------------ More: Functions and Structures * If you understand the examples above, you are in good shape. That is, the key is to be comfortable with these kinds of parameters: 1) array parameter for a structure type; and 2) pointer parameter for a structure type ------------------------------------------------------------ * * * * *