This commit is contained in:
Weber 2024-03-21 21:05:17 +00:00
parent 56cd8dff34
commit 9f977b7803

View File

@ -23,6 +23,7 @@ int compare_students(const void *a, const void *b) {
int main() { int main() {
student_t *students = NULL; student_t *students = NULL;
int students_capacity = 0; int students_capacity = 0;
int student_count = 0;
char line[1024]; char line[1024];
while (fgets(line, sizeof(line), stdin)) { while (fgets(line, sizeof(line), stdin)) {
@ -30,8 +31,8 @@ int main() {
char *name; char *name;
sscanf(line, "%d %ms", &vote_count, &name); sscanf(line, "%d %ms", &vote_count, &name);
if (students_capacity <= vote_count) { if (student_count >= students_capacity) {
students_capacity *= 2; students_capacity = (students_capacity + 1) * 2;
student_t *new_students = realloc(students, students_capacity * sizeof(student_t)); student_t *new_students = realloc(students, students_capacity * sizeof(student_t));
if (new_students == NULL) { if (new_students == NULL) {
fprintf(stderr, "Error: Memory reallocation failed\n"); fprintf(stderr, "Error: Memory reallocation failed\n");
@ -40,19 +41,22 @@ int main() {
students = new_students; students = new_students;
} }
students[vote_count].name = name; students[student_count].name = name;
students[vote_count].vote_count++; students[student_count].vote_count = vote_count;
student_count++;
} }
qsort(students, students_capacity, sizeof(student_t), compare_students); qsort(students, student_count, sizeof(student_t), compare_students);
printf("Results:\n"); printf("Results:\n");
for (int i = 0; i < students_capacity; i++) { for (int i = 0; i < student_count; i++) {
if (students[i].vote_count > 0) {
printf("%d %s\n", students[i].vote_count, students[i].name); printf("%d %s\n", students[i].vote_count, students[i].name);
students[i].name = NULL;
} }
for (int i = 0; i < student_count; i++) {
free(students[i].name);
} }
free(students);
return 0; return 0;
} }