This commit is contained in:
Weber 2024-03-21 21:14:45 +00:00
parent 9850cd5463
commit 7cc02efe4e

View File

@ -28,27 +28,27 @@ int main() {
char line[1024]; char line[1024];
while (fgets(line, sizeof(line), stdin)) { while (fgets(line, sizeof(line), stdin)) {
int vote_count; int vote_count;
char *name; char name[1024]; // Use array instead of dynamically allocated memory
sscanf(line, "%d %ms", &vote_count, &name); sscanf(line, "%d %[^\n]", &vote_count, name); // Read name until newline character
if (student_count >= students_capacity) { if (student_count >= students_capacity) {
students_capacity = (students_capacity + 1) * 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, "Chyba"); fprintf(stderr, "Error: Memory reallocation failed\n");
return 1; return 1;
} }
students = new_students; students = new_students;
} }
students[student_count].name = name; students[student_count].name = strdup(name); // Duplicate the name
students[student_count].vote_count = vote_count; students[student_count].vote_count = vote_count;
student_count++; student_count++;
} }
qsort(students, student_count, sizeof(student_t), compare_students); qsort(students, student_count, sizeof(student_t), compare_students);
printf("Results:\n"); printf("Vysledky:\n");
for (int i = 0; i < student_count; i++) { for (int i = 0; i < student_count; i++) {
printf("%d %s\n", students[i].vote_count, students[i].name); printf("%d %s\n", students[i].vote_count, students[i].name);
free(students[i].name); free(students[i].name);
@ -56,4 +56,4 @@ int main() {
free(students); free(students);
return 0; return 0;
} }