Code:
#include<stdio.h>#include<string.h>
#include<stdlib.h>
#include<stdlib.h>
//prints all records in the same order they were entered
void printRecs(int *count, char **fname, char **lname, float *grades)
{
printf("count: %d\n", *count);
//for loop to print all the arrays
int i;
printf("count: %d\n", *count);
for (i = 0; i < *count; i++) {
printf("loop count: %d\n", i);
printf("First Name: %s, Last Name: %s, Score: %.2f \n", &fname[0],
&lname[0], grades);
}
}
void addRecs(int *count, char **fname, char **lname, float *grades)
{
*count = *count + 1;
//reallocate older stuff
char **tempf = realloc(fname, *count * sizeof *tempf);
for (int i = 0; i < *count - 1; i++) {
tempf = realloc(fname, 20 * sizeof *tempf);
}
char **templ = realloc(lname, *count * sizeof *templ);
for (int i = 0; i < *count - 1; i++) {
templ = realloc(lname, 20 * sizeof *templ);
}
float *tempg = realloc(grades, *count * sizeof *tempg);
//allocate space for newest
templ[*count - 1] = (char *) malloc(20 * sizeof *lname[*count - 1]);
tempf[*count - 1] = (char *) malloc(20 * sizeof *fname[*count - 1]);
free(fname);
free(lname);
free(grades);
fname = tempf;
lname = templ;
grades = tempg;
printf("Add a record\n");
scanf("%s %s %f", &fname[*count - 1][0], &lname[*count - 1][0],
&grades[*count - 1]);
int i;
for (i = 0; i < *count; i++) {
printf("First Name: %s, Last Name: %s, Score: %.2f \n", &fname[0],
&lname[0], grades);
}
}
int main()
{
int choice = 1;
//ask user for total count of students, must be between 5 and 15
int temp = 0;
int *count = &temp;
while ((*count > 15) || (*count < 5)) {
printf
("Please indicate number of records you want to enter (min 5, max 15): ");
scanf("%d", count);
}
//read in all the data for the students
char **lname = (char **) malloc(*count * sizeof *lname);
for (int i = 0; i < *count; i++) {
lname = (char *) malloc(20 * sizeof *lname);
}
char **fname = (char **) malloc(*count * sizeof *fname);
for (int i = 0; i < *count; i++) {
fname = (char *) malloc(20 * sizeof *fname);
}
float *grades = (float *) malloc(*count * sizeof *grades);
int i;
printf
("Please input records of students (enter a new line after each record), with following format first name last name score\n");
for (i = 0; i < *count; i++) {
scanf("%s %s %f", &fname[0], &lname[0], &grades);
}
//display menu and switch inside a loop for selection
//printf("Print records (press 1)\nSearch by first name (press 2)\nSearch by last name (press 3)\nSort by score (press 4)\nSort by last name (press 5)\nFind Max Score (press 6)\nFind Min Score (press 7)\nExit the program (press 0)\n");
while (choice != 0) {
printf("Enter choice: ");
scanf("%d", &choice);
switch (choice) {
case 0:
break;
case 1:
printRecs(count, fname, lname, grades);
break;
case 2:
addRecs(count, fname, lname, grades);
break;
default:
printf("Please only enter a number from 0 to 7\n");
break;
}
}
}