Structure for dynamic arrays
What you'll learn: How to group a pointer and metadata into a single structure to manage memory that can grow or shrink.
The problem with raw pointers
Up to this point, you have likely used malloc() to create an array, storing the address in a simple pointer like int *arr. However, a pointer is forgetful. It knows where the data starts, but it has no idea how many elements are currently inside or how much total space was allocated.
If you pass a raw pointer to a function, you must also pass the size as a separate variable. If you forget to update that size variable after a realloc(), your program will likely crash or corrupt memory. To solve this, we use a struct to bundle the pointer with its "metadata."
The "Expanding Suitcase" analogy
Think of a dynamic array like a suitcase. A raw pointer is just the handle. If you only hold the handle, you don't know how big the suitcase is or if it’s full. A dynamic array structure is the entire suitcase: it contains the storage space (the pointer), a counter for how many shirts are inside (the size), and a label stating the maximum number of shirts it can hold before it bursts (the capacity).
Defining the structure
In C, a robust dynamic array structure typically requires three members:
- The Data Pointer: A pointer to the heap memory.
- Size: The number of elements currently in use.
- Capacity: The total number of slots currently allocated.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *data; // Pointer to the actual array on the heap
int size; // Number of elements currently stored
int capacity; // Total available slots before needing realloc
} IntArray;
int main() {
// Initializing our structure
IntArray myArr;
myArr.size = 0;
myArr.capacity = 5;
myArr.data = malloc(myArr.capacity * sizeof(int));
if (myArr.data == NULL) return 1; // Safety check
// Now, the struct keeps all the information in one neat package
printf("Array status: %d/%d slots used.\n", myArr.size, myArr.capacity);
free(myArr.data);
return 0;
}
Why this matters
By bundling these three variables, you create a self-contained object. When you need to resize the array, you can check if size == capacity. If it does, you know exactly when to call realloc(). This structure prevents "magic numbers" and ensures that your data and its boundaries never get separated.
Key takeaway
A dynamic array structure bundles a data pointer with size and capacity variables to keep track of memory boundaries automatically.