...

/

Dynamically Allocating Structures and Structure Members

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:

Press + to interact
C
#include <stdio.h>
#include <string.h>
typedef struct
{
char name[32];
char author[64];
char publisher[32];
int releaseYear;
int numberOfPages;
} TBook;
//TBookStore uses TBook, so it has to be declared after TBook
typedef struct
{
char address[128];
int startHour;
int endHour;
TBook booksList[1024];
int numberOfBooks;
} TBookStore;
//Receives a book and prints the data about it
void printBookData(TBook book)
{
printf("Book %s\n", book.name);
printf("\tAuthor: %s\n", book.author);
printf("\tPublisher: %s\n", book.publisher);
printf("\tRelease year: %d\n", book.releaseYear);
printf("\tNumber of pages: %d\n", book.numberOfPages);
printf("\n");
}
//Receives a book store and prints all the books inside it
void printStoreBooks(TBookStore store)
{
for(int i = 0; i < store.numberOfBooks; i++)
{
printBookData(store.booksList[i]);
}
}
int main()
{
//Create a store and set its data
TBookStore store;
strcpy(store.address, "Some finctional address");
store.startHour = 9;
store.endHour = 17;
//Add two books inside the librray.
strcpy(store.booksList[0].name, "War and Peace");
strcpy(store.booksList[0].author, "Lev Tolstoi");
strcpy(store.booksList[0].publisher, "The Russian Messenger");
store.booksList[0].releaseYear = 1865;
store.booksList[0].numberOfPages = 1225;
strcpy(store.booksList[1].name, "The Vicomte of Bragelonne");
strcpy(store.booksList[1].author, "Alexandre Dumas");
strcpy(store.booksList[1].publisher, "Unknown");
store.booksList[1].releaseYear = 1847;
store.booksList[1].numberOfPages = 2544;
//Set the number of books
store.numberOfBooks = 2;
printStoreBooks(store);
return 0;
}

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.

 ...