Pushing elements and capacity checks
What you'll learn: How to manage the available space in a dynamic array to ensure you never write data into memory you don't own.
The Suitcase Analogy
Imagine you are packing a suitcase for a trip. You have a specific amount of "capacity"—say, space for five outfits. As you pack each shirt (an "element"), you increment your count. If you try to pack a sixth shirt without getting a bigger suitcase, you’ll tear the fabric or spill over into someone else's luggage.
In C, a dynamic array is just a block of memory. Unlike a standard array, we keep track of two distinct numbers:
- Size: How many items are currently inside.
- Capacity: How many items the current block of memory can hold.
The "Check-Before-Push" Pattern
When you want to "push" (add) a new element to the end of your array, you must perform a gatekeeper check. If the size is equal to the capacity, the "suitcase" is full. You must resize the memory (usually doubling it) before the new item can safely fit.
Only after ensuring there is room do you place the item at the index of size and then increment the size counter.
Implementing the Logic
Here is how this looks in a typical "push" function:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *data;
int size;
int capacity;
} DynamicArray;
void push(DynamicArray *array, int value) {
// 1. Capacity Check: Is the suitcase full?
if (array->size == array->capacity) {
// Double the capacity (or start at 1 if 0)
int new_capacity = array->capacity == 0 ? 1 : array->capacity * 2;
// Reallocate memory to fit the new capacity
int *new_data = realloc(array->data, new_capacity * sizeof(int));
if (new_data != NULL) {
array->data = new_data;
array->capacity = new_capacity;
}
}
// 2. Add the element
array->data[array->size] = value;
// 3. Increment size
array->size++;
}
By doubling the capacity instead of just adding one extra slot, we save time. If we resized every single time we added an item, our program would spend all its energy talking to the operating system asking for memory. Doubling gives us "breathing room" for future pushes.
Key takeaway
Always verify that size < capacity before adding an element; if they are equal, you must resize the array to prevent memory corruption.