Initialization

This commit is contained in:
Kozar 2024-04-25 20:28:58 +02:00
parent c5a533ebc2
commit 6083688b7e

View File

@ -2,61 +2,71 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
// Function to compare strings for qsort int compare_names(const void *a, const void *b) {
int compare(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b); return strcmp(*(const char **)a, *(const char **)b);
} }
int main() { int main() {
int max_students; int count;
char **applications = NULL;
char buffer[100]; char buffer[100];
int num_applications = 0; char **applications;
int i, j;
// Read the maximum number of students to accept if (scanf("%d", &count) != 1 || count <= 0) {
if (scanf("%d", &max_students) != 1 || max_students <= 0) { printf("Nespravny vstup\n");
puts("Nespravny vstup");
return 1; return 1;
} }
// Allocate memory for the list of applications applications = (char **)malloc(count * sizeof(char *));
applications = (char **)malloc(max_students * sizeof(char *)); if (!applications) {
if (applications == NULL) { printf("Chyba pri alokacii pamate\n");
puts("Chyba alokacie pamate");
return 1; return 1;
} }
// Read the applications i = 0;
while (num_applications < max_students && fgets(buffer, sizeof(buffer), stdin) != NULL && buffer[0] != '\n') { while (i < count && fgets(buffer, sizeof(buffer), stdin)) {
size_t len = strlen(buffer); int len = strlen(buffer);
if (buffer[len - 1] == '\n') { if (len > 0 && buffer[len - 1] == '\n') { // Remove newline character if present
buffer[len - 1] = '\0'; // Remove the newline character buffer[len - 1] = '\0';
} }
applications[num_applications] = strdup(buffer); int found = 0;
if (applications[num_applications] == NULL) { for (j = 0; j < i; j++) {
puts("Chyba alokacie pamate"); if (strcmp(applications[j], buffer) == 0) {
return 1; found = 1;
break;
}
}
if (!found) {
applications[i] = strdup(buffer);
i++;
} }
num_applications++;
} }
// Check if any applications were read if (i == 0) {
if (num_applications == 0) { printf("Ziadne prihlasky\n");
puts("Ziadne prihlasky");
return 1; return 1;
} }
// Sort the applications alphabetically // Sort the applications alphabetically
qsort(applications, num_applications, sizeof(char *), compare); qsort(applications, i, sizeof(char *), compare_names);
// Print the accepted students printf("Prijati studenti:");
puts("Prijati studenti:"); for (j = 0; j < i; j++) {
for (int i = 0; i < num_applications; i++) { printf("%s\n", applications[j]);
printf("%s\n", applications[i]);
free(applications[i]); // Free memory for each application
} }
free(applications); // Free the array of applications if (count < i) {
printf("Neprijati studenti:");
for (; j < i; j++) {
printf("%s\n", applications[j]);
}
}
// Free allocated memory
for (j = 0; j < i; j++) {
free(applications[j]);
}
free(applications);
return 0; return 0;
} }