#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义借阅记录结构体
typedef struct {
char borrower[50];
char borrowDate[20];
char returnDate[20];
} BorrowRecord;
// 定义书籍结构体
typedef struct {
char title[100];
char author[50];
int year;
float price;
BorrowRecord **borrowRecords;
int recordCount;
int capacity;
} Book;
// 初始化书籍
Book* createBook(const char* title, const char* author, int year, float price) {
Book *book = (Book*)malloc(sizeof(Book));
if (book == NULL) {
perror("内存分配失败");
return NULL;
}
strcpy(book->title, title);
strcpy(book->author, author);
book->year = year;
book->price = price;
book->recordCount = 0;
book->capacity = 2;
book->borrowRecords = (BorrowRecord**)malloc(book->capacity * sizeof(BorrowRecord*));
if (book->borrowRecords == NULL) {
perror("内存分配失败");
free(book);
return NULL;
}
return book;
}
// 动态添加借阅记录
void addBorrowRecord(Book *book, const char* borrower, const char* borrowDate, const char* returnDate) {
if (book->recordCount >= book->capacity) {
book->capacity *= 2;
book->borrowRecords = (BorrowRecord**)realloc(book->borrowRecords, book->capacity * sizeof(BorrowRecord*));
if (book->borrowRecords == NULL) {
perror("内存分配失败");
return;
}
}
book->borrowRecords[book->recordCount] = (BorrowRecord*)malloc(sizeof(BorrowRecord));
if (book->borrowRecords[book->recordCount] == NULL) {
perror("内存分配失败");
return;
}
strcpy(book->borrowRecords[book->recordCount]->borrower, borrower);
strcpy(book->borrowRecords[book->recordCount]->borrowDate, borrowDate);
strcpy(book->borrowRecords[book->recordCount]->returnDate, returnDate);
book->recordCount++;
}
// 查询书籍信息
void printBookInfo(Book *book) {
printf("书名: %s\n", book->title);
printf("作者: %s\n", book->author);
printf("出版年份: %d\n", book->year);
printf("价格: %.2f\n", book->price);
printf("借阅记录:\n");
for (int i = 0; i < book->recordCount; i++) {
printf("借阅者: %s, 借阅日期: %s, 归还日期: %s\n",
book->borrowRecords[i]->borrower,
book->borrowRecords[i]->borrowDate,
book->borrowRecords[i]->returnDate);
}
}
// 释放所有动态分配的内存
void freeBook(Book *book) {
for (int i = 0; i < book->recordCount; i++) {
free(book->borrowRecords[i]);
}
free(book->borrowRecords);
free(book);
}
int main() {
Book *book = createBook("C语言程序设计", "谭浩强", 2017, 59.0);
addBorrowRecord(book, "张三", "2023-10-01", "2023-10-15");
addBorrowRecord(book, "李四", "2023-11-01", "2023-11-15");
printBookInfo(book);
freeBook(book);
return 0;
}