Chapter 6. Data Structures and Dynamic Memory: Building bridges

image with no caption

Sometimes, a single struct is simply not enough.

To model complex data requirements, you often need to link structs together. In this chapter, you’ll see how to use struct pointers to connect custom data types into large, complex data structures. You’ll explore key principles by creating linked lists. You’ll also see how to make your data structures cope with flexible amounts of data by dynamically allocating memory on the heap, and freeing it up when you’re done. And if good housekeeping becomes tricky, you’ll also learn how valgrind can help.

Do you need flexible storage?

image with no caption

You’ve looked at the different kinds of data that you can store in C, and you’ve also seen how you can store multiple pieces of data in an array. But sometimes you need to be a little more flexible.

Imagine you’re running a travel company that arranges flying tours through the islands. Each tour contains a sequence of short flights from one island to the next. For each of those islands, you will need to record a few pieces of information, such as the name of the island and the hours that its airport is open. So how would you record that?

You could create a struct to represent a single island:

typedef struct { char *name; char *opens; char ...

Get Head First C now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.