diff --git a/cv10/program.c b/cv10/program.c index 4f97621..0a35608 100644 --- a/cv10/program.c +++ b/cv10/program.c @@ -21,12 +21,14 @@ int main() { char **students = NULL; int num_students = 0; + printf("Enter the maximum number of students that can be accepted: "); if (scanf("%d\n", &max_students) != 1 || max_students <= 0) { puts("Invalid input for the number of students."); return 1; } + students = (char **)malloc(max_students * sizeof(char *)); if (students == NULL) { puts("Memory allocation failed."); @@ -34,28 +36,29 @@ int main() { } printf("Enter student names (press Enter twice to stop):\n"); - while (fgets(name, MAX_NAME_LENGTH, stdin)) { - if (name[strcspn(name, "\n")] = '\0', !*name) + while (fgets(name, MAX_NAME_LENGTH, stdin) && num_students < max_students) { + name[strcspn(name, "\n")] = '\0'; + if (strlen(name) == 0) { break; + } - int is_duplicate = 0; + + int duplicate = 0; for (int i = 0; i < num_students; i++) { if (strcmp(students[i], name) == 0) { - is_duplicate = 1; + duplicate = 1; break; } } - if (!is_duplicate) { - if (num_students < max_students) { - students[num_students] = strdup(name); - if (students[num_students] == NULL) { - puts("Memory allocation failed."); - free_memory(students, num_students); - return 1; - } - num_students++; + if (!duplicate) { + students[num_students] = strdup(name); + if (students[num_students] == NULL) { + puts("Memory allocation failed."); + free_memory(students, num_students); + return 1; } + num_students++; } } @@ -65,15 +68,14 @@ int main() { return 1; } - qsort(students, num_students, sizeof(char *), compare); + qsort(students, num_students, sizeof(char *), compare); puts("Accepted students:"); for (int i = 0; i < num_students; i++) { puts(students[i]); } - free_memory(students, num_students); + free_memory(students, num_students); return 0; } -