Course contentsShow
← C
Lesson 1214 of 1,21916. Practice and ProjectsFree lesson

Implementing a dynamic array for storage

Implementing a dynamic array for storage

What you'll learn: How to create a resizable container using malloc and realloc to store an unpredictable number of data records.

The Problem: Fixed vs. Flexible

In our Data Store project, we don't know if a user will save five records or five thousand. If we declare a standard array like Record data[100];, we hit a wall the moment the 101st item arrives. To build a professional tool, we need a structure that grows on demand. Think of it like a dining table with leaves: you start with a small surface, but as more guests arrive, you swap it out for a larger one.

The Strategy: Capacity and Count

To manage this, we need to track two different numbers:

  1. Count: How many items are currently inside.
  2. Capacity: How many items the current block of memory can hold.

When count == capacity, we are out of room. We then use realloc to ask the operating system for a larger block of memory, copy our data over, and update our capacity.

Implementing the Growth Logic

Here is how you structure the core of your storage engine. We typically double the capacity each time we run out of space to keep the program efficient.

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int id;
    char name[50];
} Record;

typedef struct {
    Record *items;
    int count;
    int capacity;
} DataStore;

void add_record(DataStore *store, Record new_item) {
    // Check if we are full
    if (store->count == store->capacity) {
        // Double the capacity (handle initial case where capacity is 0)
        int new_capacity = store->capacity == 0 ? 4 : store->capacity * 2;
        
        // Reallocate memory to the new size
        Record *new_items = realloc(store->items, new_capacity * sizeof(Record));
        
        if (new_items) {
            store->items = new_items;
            store->capacity = new_capacity;
        }
    }

    // Add the item and increment count
    store->items[store->count] = new_item;
    store->count++;
}

Why Realloc?

The realloc function is the hero here. It tries to expand your current memory block in place. If it can't (because another program is using the space next door), it finds a brand-new, larger spot, moves all your data there automatically, and frees the old spot. This allows your Data Store to stay organized without losing a single byte of user information.

Key takeaway

A dynamic array uses a capacity variable to trigger realloc, ensuring your data store grows automatically as more records are added.