/* ========================================================================== */ /* */ /* structures.c */ /* (c) 2017 K. J. Rock */ /* */ /* This shows how to create and use a structure with pointers */ /* linked into a list */ /* ========================================================================== */ #include #include #include struct db { int id; int age; float salary; struct db *next; }; struct db *head, *ep, *node, *temp; int main() { srand((unsigned) time(NULL)); // randomize by seeding from time temp = (struct db *) malloc (sizeof(struct db)); temp->next = NULL; // define end of list with guard value NULL temp->id = 42; // instantiate the founder's info temp->age = rand() % 40 + 20; temp->salary = 35080.15 + (rand() % 1250); head = temp; // store beginning of list as head pointer // allocate space & instantiate the rest of the crew for (int i=1; i<27; i++) { node = (struct db *) malloc (sizeof(struct db)); temp->next = node;// add new node to end of growing list node->next = NULL;// set end of list with our standard guard value temp = node; // keep track of this node so you can add to it temp->id = i; // fill data fields of new node temp->age = rand() % 40 + 20; // no employees under 20 temp->salary = (float) ((rand() % 40000) + 60000); // min salary 60000 } ep = head; // set employee pointer to start of list while (ep != NULL) { printf("Employee #%2d is %2d years old earning $%6.2f \n", ep->id, ep->age, ep->salary); ep = ep->next; // step to next employee } float sum = 0; int count = 0; int age = 0; ep = head; while (ep != NULL) { age += ep->age; sum += ep->salary; count++; ep = ep->next; } printf("\nPayroll $%8.2f \n", sum); printf("average paycheck $%8.2f \n", sum / count ); printf("Average age %2d \n", age / count ); // integer divide so rough estimate //printf("%2d \n", count); }