/* structs_3.c create a struct definition declare, initialize and print an AUTOMATIC ARRAY of struct variables use of the [] and . operators */ #include #include #include #define MAX_PERSONS 5 typedef struct { char *name; int age; } Person; /* Person is now a data type */ int ages[] = { 48, 23, 21, 43, 52 }; char *names[] = { "Mark", "Hassan", "Stephanie", "Tim", "Rich" }; int main(int argc, char *argv[]) { Person array[MAX_PERSONS]; int i; /* Populate each Person in the array from the global data above main */ for (i = 0; i < MAX_PERSONS; i++) { array[i].name = (char *)malloc((strlen(names[i]) + 1) * sizeof(char)); strcpy(array[i].name, names[i]); array[i].age = ages[i]; } /* print the array */ printf("Slot\tName\tAge\t\n"); for (i = 0; i < MAX_PERSONS; i++) printf("%2d\t%s\t%2d\n", i, array[i].name, array[i].age); printf("\n"); /* free the strings in the array */ for (i = 0; i < MAX_PERSONS; i++) free(array[i].name); return 0; }