#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char* title;
char* author;
int year;
} Book;
// Инициализация книги (выделяет память под строки)
void book_init(Book* b, const char* title, const char* author, int year) {
b->title = strdup(title); // выделяет память и копирует строку
b->author = strdup(author);
b->year = year;
if (!b->title || !b->author) {
fprintf(stderr, "Memory allocation error\n");
exit(1);
}
}
// Освобождение памяти внутри книги
void book_destroy(Book* b) {
free(b->title);
free(b->author);
}
// Вывод книги (аналог перегруженного operator<<)
void book_print(const Book* b) {
printf("\"%s\" by %s (%d)\n", b->title, b->author, b->year);
}
// Сравнение для qsort по году
int cmp_by_year(const void* a, const void* b) {
const Book* ba = (const Book*)a;
const Book* bb = (const Book*)b;
return ba->year - bb->year;
}
int main() {
Book* library = NULL;
int count = 0;
// Добавление книг с ручным управлением памятью (realloc)
// Книга 1
library = realloc(library, (count + 1) * sizeof(Book));
if (!library) { fprintf(stderr, "realloc failed\n"); return 1; }
book_init(&library[count], "The C++ Programming Language", "Bjarne Stroustrup", 2013);
count++;
// Книга 2
library = realloc(library, (count + 1) * sizeof(Book));
if (!library) { fprintf(stderr, "realloc failed\n"); return 1; }
book_init(&library[count], "Effective Modern C++", "Scott Meyers", 2014);
count++;
// Книга 3
library = realloc(library, (count + 1) * sizeof(Book));
if (!library) { fprintf(stderr, "realloc failed\n"); return 1; }
book_init(&library[count], "The Art of Computer Programming", "Donald Knuth", 1968);
count++;
printf("Before sorting:\n");
for (int i = 0; i < count; ++i) book_print(&library[i]);
// Сортировка qsort
qsort(library, count, sizeof(Book), cmp_by_year);
printf("\nSorted by year:\n");
for (int i = 0; i < count; ++i) book_print(&library[i]);
// Очистка памяти
for (int i = 0; i < count; ++i) book_destroy(&library[i]);
free(library);
return 0;
}