CodeBlanks Logo Icon CodeBlanks

Putting it together

  • C course
  • Beginner
  • Lesson 116/116
  • 6 min

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.

Practice 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).

Starter code

main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Book {
    char title[32];
    int year;
};

void print_book(struct Book b) {
    printf("%s %d\n", b.title, b.year);
}

// Allocate a 2-book array with malloc; assign titles with strcpy; print with print_book; release with free
int main(void) {
    return 0;
}

Sample solution

main.c
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);

Expected output

War and Peace 1869
Anna Karenina 1877

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match concept to usage

Term Meaning
malloc Dynamic array
books[0] First element
print_book Printing
free Releasing

2 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 Correct answer

Explanation: In C pointer and array are equivalent; books[0] is valid.

3 Fill in the blank: dynamic array allocation

Question
struct Book *books = ____(2 * sizeof(struct Book));
Answer
struct Book *books = malloc(2 * sizeof(struct Book));

Explanation: malloc(2 * sizeof(struct Book)) allocates space for two books.

All lessons in Beginner