O'Reilly logo

Head First C by Dawn Griffiths, David Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 *closes; } island; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required