C
Putting it together
Combine all parts into a working final app.
Putting it together: dynamic catalog
In the final lesson you combine all pieces: struct Book, print_book, malloc and free. You create a dynamic array of books, print them and release the memory.
struct Book *books = malloc(2 * sizeof(struct Book));
strcpy(books[0].title, "Suç ve Ceza");
books[0].year = 1866;
print_book(books[0]);
free(books);
Here books is a pointer but used like an array with [index]. The chain books[0].title treats the pointer as an array. This shows the power of pointer-array equivalence in C.
Summary of the dynamic catalog
In this project we built a book catalog in five steps: struct Book, an array of books, a print_book function, dynamic memory with malloc and the final combination.
struct Book *books = malloc(2 * sizeof(struct Book));
/* assign two books */
print_book(books[0]);
print_book(books[1]);
free(books);
This is the skeleton of a real C app: data model, functions, memory management and combination. Extending to larger projects is just multiplying these pieces with more data and more functions.
Exercise Build and print the dynamic catalog
Allocate a two-book dynamic array with malloc(2 * sizeof(struct Book)). With strcpy set books[0].title to "War and Peace", books[1].title to "Anna Karenina"; assign years 1869 and 1877. Print both books with print_book; release with free(books).
Show example solution
struct Book *books = malloc(2 * sizeof(struct Book));
strcpy(books[0].title, "War and Peace");
books[0].year = 1869;
strcpy(books[1].title, "Anna Karenina");
books[1].year = 1877;
print_book(books[0]);
print_book(books[1]);
free(books);
Test yourself
-
Match concept to usage
- malloc
- Dynamic array
- books[0]
- First element
- print_book
- Printing
- free
- Releasing
-
How does books[0].title work when books is a pointer?
- The member is deleted
- It does not work; error
- Only -> operator works
- The pointer is treated as an array
Show answer
The pointer is treated as an array — In C pointer and array are equivalent; books[0] is valid.
-
Fill in the blank: dynamic array allocation
struct Book *books = ____(2 * sizeof(struct Book));
Show answer
struct Book *books = malloc(2 * sizeof(struct Book));
Next lesson: Beginner section exam