This commit is contained in:
Weber 2024-03-22 00:14:06 +00:00
parent fb7e53f429
commit 8a22ebd718

View File

@ -8,8 +8,8 @@ typedef struct student {
} student_t; } student_t;
int compare_students(const void *a, const void *b) { int compare_students(const void *a, const void *b) {
const student_t *student_a = (const student_t *)a; const student_t *student_a = *(const student_t **)a;
const student_t *student_b = (const student_t *)b; const student_t *student_b = *(const student_t **)b;
if (student_a->vote_count > student_b->vote_count) { if (student_a->vote_count > student_b->vote_count) {
return -1; return -1;
@ -21,7 +21,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; int student_count = 0;
@ -33,8 +33,8 @@ int main() {
int found = 0; int found = 0;
for (int i = 0; i < student_count; i++) { for (int i = 0; i < student_count; i++) {
if (strcmp(students[i].name, name) == 0) { if (strcmp(students[i]->name, name) == 0) {
students[i].vote_count += vote_count; students[i]->vote_count += vote_count;
found = 1; found = 1;
break; break;
} }
@ -43,7 +43,7 @@ int main() {
if (!found) { if (!found) {
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, "Error: Memory reallocation failed\n"); fprintf(stderr, "Error: Memory reallocation failed\n");
return 1; return 1;
@ -51,18 +51,20 @@ int main() {
students = new_students; students = new_students;
} }
students[student_count].name = strdup(name); students[student_count] = malloc(sizeof(student_t));
students[student_count].vote_count = vote_count; students[student_count]->name = strdup(name);
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("Vysledky:\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);
free(students[i]);
} }
free(students); free(students);