diff --git a/cv5/program.c b/cv5/program.c index 8e10af4..4fa2b9a 100644 --- a/cv5/program.c +++ b/cv5/program.c @@ -23,6 +23,7 @@ int compare_students(const void *a, const void *b) { int main() { student_t *students = NULL; int students_capacity = 0; + int student_count = 0; char line[1024]; while (fgets(line, sizeof(line), stdin)) { @@ -30,8 +31,8 @@ int main() { char *name; sscanf(line, "%d %ms", &vote_count, &name); - if (students_capacity <= vote_count) { - students_capacity *= 2; + if (student_count >= students_capacity) { + students_capacity = (students_capacity + 1) * 2; student_t *new_students = realloc(students, students_capacity * sizeof(student_t)); if (new_students == NULL) { fprintf(stderr, "Error: Memory reallocation failed\n"); @@ -40,19 +41,22 @@ int main() { students = new_students; } - students[vote_count].name = name; - students[vote_count].vote_count++; + students[student_count].name = name; + 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"); - for (int i = 0; i < students_capacity; i++) { - if (students[i].vote_count > 0) { - printf("%d %s\n", students[i].vote_count, students[i].name); - students[i].name = NULL; - } + for (int i = 0; i < student_count; i++) { + printf("%d %s\n", students[i].vote_count, students[i].name); } + for (int i = 0; i < student_count; i++) { + free(students[i].name); + } + free(students); + return 0; } \ No newline at end of file