In Python, lists grow automatically. In C, you manage this manually:
typedef struct {
Token *items; // Pointer to array
long count; // Elements used
long capacity; // Elements allocated
} Token_Array;
// Append with automatic growth
void da_append(Token_Array *arr, Token tok) {
if (arr->count >= arr->capacity) {
// Double capacity when full!
arr->capacity = arr->capacity == 0 ? 16 : arr->capacity * 2;
arr->items = realloc(arr->items, arr->capacity * sizeof(Token));
}
arr->items[arr->count++] = tok;
}
Why Double?
| Appends | Old Cap | New Cap | Copies |
|---|---|---|---|
| 17th | 16 | 32 | 16 |
| 33rd | 32 | 64 | 32 |
Amortized O(1) per append. If we grew by +1 each time, it would be O(n)!