From b57c6d5ce98f1cbad1f22e2907d2fac4df0b835c Mon Sep 17 00:00:00 2001 From: Vasylenko Date: Tue, 23 Apr 2024 11:22:59 +0200 Subject: [PATCH] =?UTF-8?q?=E2=80=9Cprogram=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cv10/program.c | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) 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; } -