pvjc24/cv10/program.c
2024-04-23 11:05:21 +02:00

80 lines
1.8 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LENGTH 100
int compare(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
void free_memory(char **array, int length) {
for (int i = 0; i < length; i++) {
free(array[i]);
}
free(array);
}
int main() {
int max_students;
char name[MAX_NAME_LENGTH];
char **students = NULL;
int num_students = 0;
if (scanf("%d\n", &max_students) != 1 || max_students <= 0) {
puts("Nespravny vstup");
return 1;
}
students = (char **)malloc(max_students * sizeof(char *));
if (students == NULL) {
puts("Memory allocation failed");
return 1;
}
while (fgets(name, MAX_NAME_LENGTH, stdin)) {
name[strcspn(name, "\n")] = 0;
if (strlen(name) == 0) {
break;
}
int duplicate = 0;
for (int i = 0; i < num_students; i++) {
if (strcmp(students[i], name) == 0) {
duplicate = 1;
break;
}
}
if (!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 (num_students == 0) {
puts("Ziadne prihlasky");
free(students);
return 1;
}
qsort(students, num_students, sizeof(char *), compare);
puts("Prijati studenti:");
for (int i = 0; i < num_students; i++) {
puts(students[i]);
}
free_memory(students, num_students);
return 0;
}