/* structs_4.c create a struct definition declare, initialize, print and free a DYNAMIC ARRAY of structs use of the . and -> operators */ #include #include #include #define INITIAL_ARRAY_MAX 25 #define MAX_NAME_LENGTH 10 typedef struct { char *name; int age; } Person; /* Person is now a data type */ /* ASSUME INPUT FILE OF THIS FORMAT (alignment unimportant) Mark 48 Hassan 23 Stephanie 21 Tim 43 Rich 52 */ int main(int argc, char *argv[]) { Person **array; /* pointer to dynamic array of Person* */ int i; int count = 0; /* actual # of structs read from file */ FILE *inFile; /* temp variables to read data from file */ char name[MAX_NAME_LENGTH]; int age; if (!(inFile = fopen("input.txt", "r"))) { fprintf(stderr, "Can't open input.txt!!\n\n"); exit(1); } /* allocate the array */ array = (Person **)malloc(INITIAL_ARRAY_MAX * sizeof(Person *)); /* populate the array */ printf("Reading from input.txt\n"); while(fscanf(inFile,"%s%d",name,&age) == 2) { printf("reading... %s %d\n", name, age); array[count] = (Person *)malloc(sizeof(Person)); array[count]->name = (char *)malloc((strlen(name) + 1) * sizeof(char)); strcpy(array[count]->name, name); array[count]->age = age; count++; } fclose(inFile); /* print the array */ printf("\nPrinting the array:\n"); printf("Slot\tName\tAge\t\n"); for (i = 0; i < count; i++) printf("%2d\t%s\t%2d\n", i, array[i]->name, array[i]->age); printf("\n"); /* free the strings, the structs and then the array */ for (i = 0; i < count; i++) { free(array[i]->name); /* the string */ free(array[i]); /* the struct */ } free(array); /* the dynamic array */ return 0; }