Dynamically Allocating Structures and Structure Members
Learn to dynamically allocate structures.
Introduction
We can dynamically allocate structures like we allocate any other data type.
Let’s revisit the bookstore example. Here’s the code for reference:
We have a TBookStore structure, which contains a list of books. We defined the list of books as an array of 1,024 elements. This array can’t grow, and we can’t decide its size at compile time since we don’t know the number of books.
Moreover, up to this point, we allocated each structure on the stack. We can run into a stack overflow exception if the structures are too big. It means we can’t use a huge number as the size of our array instead of 1,024 since we may run out of space.
Note: It’s good practice to dynamically allocate large structures. Avoid placing them on the stack to avoid a stack overflow error.
Dynamically allocating TPoint
Before we fix the bookstore code, let’s take a simple example and learn how to allocate a single structure.
Let’s reconsider the point structure.
typedef struct
{
int x;
int y;
} TPoint;
Recall that it represents a two-dimensional point in space. The coordinates are x and y.
To dynamically allocate a TPoint, we can use malloc or calloc.