UMBC CS 201, Fall 06
Fall '06

CSEE | 201 | 201 F'06 | lectures | news | help

Arrays of Structures

It should come to as no surprise that since we can create variables which are structures, we can also create arrays of structures, just like we create arrays of int, float, or some other data type.

Recall that declaring an array of ints

int grades[30]; allocates contiguous memory for the integers and uses the name of the array as a pointer to the array.

We can then access the elements of the array using subscripts. Each of the elements is an int.

grades[3] = 90; Similarly, we can declare an array of a particular type of structure. We can declare an array of 'struct point's as struct point points[5]; or, using the typefdef alias POINT, we can equivalently write POINT points[5];

In an array of ints, each element (like grades[3]) is an int.
So too, in an array of 'struct point's, each element (like points[3]) is a 'struct point'.

We reference the members of the structures in the array using the dot operator.

points[3].x is the x-coordinate of the 4th element of the array.

points[0].y is the y-coordinate of the 1st element of the array.

We can assign array elements to them as in this code fragment POINT points[30]; POINT point1; /* assuming the array elements are initialized */ /* assign (copy) the 11th element into point1 */ point1 = points[10]; /* print the x-coordinate of the 2nd element */ printf ("%d", points[1].x); /* print the y-coordinate of the 2nd element */ printf ("%d", points[1].y);

CSEE | 201 | 201 F'06 | lectures | news | help

Tuesday, 22-Aug-2006 07:14:09 EDT