Presentation is loading. Please wait.

Presentation is loading. Please wait.

Array of Structures A structure holds only one record But a record

Similar presentations


Presentation on theme: "Array of Structures A structure holds only one record But a record"— Presentation transcript:

1 Array of Structures A structure holds only one record But a record
can contain many fields To deal with a collection of records, use an Array of structures How? /* define a struct */ typedef struct{int x,y;} point; ... /* in a function, declare an array of structs */ point polygon_point[10]; 142 T -1

2 How to access the fields of a struct in
an array of structs? combine what we know about structs and arrays polygon_point[6].x is the x coordinate of the 7th point of the polygon In the memory an int x y a struct polygon_point[0] polygon_point[1] polygon_point is a pointer of type pointer to a struct point (point *) 142 T -2

3 Pointers and arrays of structs
polygon_point is the name of an array Array expression Pointer expression polygon_point[2] *(polygon_point+2) polygon_point[2].x (*(polygon_point+2)).x parentheses are important! or (polygon_point+2)->x 142 T -3

4 Using arrays of structs
Drawing the polygon: int main(void) { ... GP142_point polygon[5]; for(i=0; i<4; i++) /*Connect point i to point i+1*/ GP142_lineP(BLACK,polygon[i], polygon[i+1],0); /*Connect point 4 to point 0*/ GP142_lineP(BLACK,polygon[4], polygon[5],0); } 142 T - 4

5 void draw_poly(GP142_point polygon[5]) int i;
Or with a function int main(void) { ... GP142_point polygon[5]; /* draw the polygon */ draw_poly(polygon) } void draw_poly(GP142_point polygon[5]) int i; /*Connect point i to point i+1*/ GP142_lineP(BLACK,polygon[i], polygon[i+1],0); /* Connect point 4 to point 0 */ GP142_lineP(BLACK,polygon[4], polygon[5],0); passed by reference (address is copied) ( from a single structure, all the members of the struct are copied) 142 T -5

6 Another example Sorting an array of structures typedef struct {
char name[MAX_NAME + 1]; int id; double score; } student_record; Given an array of struct student_record a[5]; sort a by score use insertion sort on a[].score sort a by alphabetical order of the names use insertion sort on a[].name (compare using strcmp) 142 T - 6

7 char name[MAX_NAME + 1]; int id; double score; } student_record; ...
Type Quiz typedef struct { char name[MAX_NAME + 1]; int id; double score; } student_record; ... student_record a[MAX_STUDENTS]; Expression Type a student_record * a[0] student_record a[5].name char * a[4].id int &a[6].score double * a[2].name[1] char a->score double 142 T - 7


Download ppt "Array of Structures A structure holds only one record But a record"

Similar presentations


Ads by Google