Chapter 6. Data Structures and Dynamic Memory: Building bridges
Sometimes, a single struct is simply not enough.
To model complex data requirements, you often need to link struct
s
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?
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.