I would focus on these lines first:
Code:
LibraryType* library = malloc(sizeof(LibraryType));
BookCollectionType* book = malloc(sizeof(BookCollectionType));
addBook(book, "The Hunger Games", 2012, 405.5);
addBook(book, "Twilight", 2007, 302);
addBook(book, "The Martian", 2015, 203.2);
Basically, why do you have a library variable, and then also have a book variable?
I would expect something like this instead:
Code:
LibraryType* library = malloc(sizeof(LibraryType));
library->bookCollection[0] = malloc(sizeof(BookCollectionType));
library->numCollections = 1;
addBook(library->bookCollection[0], "The Hunger Games", 2012, 405.5);
addBook(library->bookCollection[0], "Twilight", 2007, 302);
addBook(library->bookCollection[0], "The Martian", 2015, 203.2);
So the idea is that you have a library that consists of one or more book collections. You create a book collection and add three books to that collection. Notice that I added a member named numCollections to LibraryType, so it should look like this:
Code:
typedef struct{
char* libraryName;
BookCollectionType* bookCollection[MAX_BOOKS];
int numCollections;
}LibraryType;
This is akin to what you did with BookCollectionType.
Having done this, you do something with the library, e.g., print the books, and then when done, you clean up:
Code:
for (int i = 0; i < library->numCollections; i++)
{
for (int j = 0; j < library->bookCollection[i]->numBooks; j++)
{
free(library->bookCollection[i]->books[j]);
}
free(library->bookCollection[i]);
}
free(library);
Note that your named constants are poorly named:
- MAX_BOOKS sounds like the maximum number of books, but you're using it to mean the maximum number of book collections, so it would be better named MAX_BOOK_COLLECTIONS
- MAX_PAGES sounds like the maximum number of pages in a book, but you're using it to mean the maximum number of books in a collection, so it would be better named MAX_BOOKS