A C array has a fixed size, chosen when you write the program. Real programs often do not know in advance how many items they will need: how many students will enrol, how many lines a file has. The answer is a dynamic array, a block of heap memory that grows with realloc as items are added. This is how Python lists, Java’s ArrayList and C++’s vector work inside. This lesson builds one step by step.
In this lesson you will learn
- Keeping size and capacity in a struct
- Growing a block safely with
realloc - Why doubling the capacity is fast
- Storing strings in a dynamic array of pointers
- Removing items with
memmoveand shrinking to fit
You should know dynamic memory allocation, structures and pointers.
A Growable Array of Integers
#include <stdio.h>
#include <stdlib.h>
/* A growable array of ints, like a simple ArrayList or Python list */
typedef struct {
int *data;
size_t size; /* items in use */
size_t capacity; /* items allocated */
} IntVec;
void vec_init(IntVec *v) {
v->data = NULL;
v->size = 0;
v->capacity = 0;
}
int vec_push(IntVec *v, int value) {
if (v->size == v->capacity) {
size_t new_cap = v->capacity ? v->capacity * 2 : 4;
int *tmp = realloc(v->data, new_cap * sizeof *tmp);
if (tmp == NULL)
return 0; /* old block is still valid */
v->data = tmp;
v->capacity = new_cap;
printf(" grew to capacity %zu\n", new_cap);
}
v->data[v->size++] = value;
return 1;
}
void vec_free(IntVec *v) {
free(v->data);
vec_init(v);
}
int main(void) {
IntVec marks;
vec_init(&marks);
for (int i = 1; i <= 10; i++)
if (!vec_push(&marks, i * 7)) {
puts("out of memory");
return 1;
}
printf("size %zu, capacity %zu\n", marks.size, marks.capacity);
for (size_t i = 0; i < marks.size; i++)
printf("%d ", marks.data[i]);
printf("\n");
vec_free(&marks);
printf("after free: size %zu, data %s\n", marks.size, marks.data ? "set" : "NULL");
return 0;
}
Output
grew to capacity 4
grew to capacity 8
grew to capacity 16
size 10, capacity 16
7 14 21 28 35 42 49 56 63 70
after free: size 0, data NULL
IntVeckeeps three things together: a pointer to the items, how many are in use (size) and how many fit in the block (capacity).- When
sizereachescapacity,vec_pushasksreallocfor a block twice as big.reallockeeps the existing items, moving them to a new place if necessary. - The result goes into
tmpfirst. Ifreallocfails it returnsNULLbut the old block is still valid. Writingv->data = realloc(v->data, ...)directly would lose the only pointer to it and leak the memory. - Calling
realloc(NULL, n)behaves likemalloc(n), so the very first push needs no special case. - Ten pushes needed only three allocations: capacity went 4, 8, 16. Because the capacity doubles, the average cost of each push stays constant, however many items you add.
vec_freereleases the block and resets the struct, so a dangling pointer is never left behind.
A Dynamic Array of Strings
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Read words into a growing array of strings, then shrink it to fit */
int main(void) {
const char *input[] = {"Padma", "Meghna", "Jamuna", "Karnaphuli", "Teesta", "Surma"};
size_t n_input = sizeof input / sizeof input[0];
char **rivers = NULL;
size_t size = 0, cap = 0;
for (size_t i = 0; i < n_input; i++) {
if (size == cap) {
size_t new_cap = cap ? cap * 2 : 2;
char **tmp = realloc(rivers, new_cap * sizeof *tmp);
if (!tmp) { perror("realloc"); break; }
rivers = tmp;
cap = new_cap;
}
rivers[size] = malloc(strlen(input[i]) + 1); /* +1 for '\0' */
if (!rivers[size]) { perror("malloc"); break; }
strcpy(rivers[size], input[i]);
size++;
}
printf("stored %zu rivers, capacity %zu\n", size, cap);
/* remove the item at index 1 by shifting the rest left */
free(rivers[1]);
memmove(&rivers[1], &rivers[2], (size - 2) * sizeof *rivers);
size--;
/* shrink the block so no space is wasted */
char **fit = realloc(rivers, size * sizeof *fit);
if (fit) { rivers = fit; cap = size; }
printf("after removing one: %zu items, capacity %zu\n", size, cap);
for (size_t i = 0; i < size; i++)
printf(" %zu: %s\n", i, rivers[i]);
for (size_t i = 0; i < size; i++)
free(rivers[i]);
free(rivers);
return 0;
}
Output
stored 6 rivers, capacity 8
after removing one: 5 items, capacity 5
0: Padma
1: Jamuna
2: Karnaphuli
3: Teesta
4: Surma
- Here the array holds
char *pointers. Each river name gets its ownmallocblock ofstrlen + 1bytes, the extra byte being for the'\0'terminator. - To remove item 1, its string is freed first, then
memmoveshifts the later pointers one place left.memmoveis used instead ofmemcpybecause the source and destination overlap. - A final
reallocto exactlysizeitems gives back the unused capacity. This is optional, and worth it only when the array will not grow again. - Cleaning up takes two stages: free every string, then free the array of pointers.
Fixed Array or Dynamic Array?
Fixed array int a[100] | Dynamic array | |
|---|---|---|
| Size | Chosen when you write the code | Grows while the program runs |
| Memory | Stack or static storage | Heap |
| Freeing | Automatic | You must call free |
| Best for | Small, known sizes | Unknown or large amounts of data |
Common Mistakes
- Assigning
realloc‘s result straight back to the only pointer, which leaks the block if it fails. - Growing by one item at a time. Every push may then copy the whole array, making n pushes take about n² steps.
- Keeping pointers into the old block after
realloc. The data may have moved, so old pointers are invalid. - Forgetting the
+ 1for the terminator when copying strings.
Practice Exercises
Exercise 1. Add int vec_pop(IntVec *v, int *out) that removes the last item, stores it in *out and returns 1, or returns 0 if the vector is empty.
Show answer
int vec_pop(IntVec *v, int *out) {
if (v->size == 0) return 0;
*out = v->data[--v->size];
return 1;
}
Exercise 2. Write int vec_insert(IntVec *v, size_t pos, int value) that inserts at position pos, shifting later items right.
Show answer
int vec_insert(IntVec *v, size_t pos, int value) {
if (pos > v->size) return 0;
if (!vec_push(v, 0)) return 0; /* makes room, size grows by 1 */
memmove(&v->data[pos + 1], &v->data[pos],
(v->size - 1 - pos) * sizeof v->data[0]);
v->data[pos] = value;
return 1;
}
Frequently Asked Questions
Why double the capacity instead of adding a fixed amount?
With doubling, the total copying work over n pushes is less than 2n, so each push costs a constant amount on average. Adding a fixed amount, such as 10 more each time, makes the total copying grow with n², which becomes very slow for large arrays.
Does realloc always move the data?
No. If there is free space right after the current block, realloc may simply extend it. You cannot know which will happen, so always use the pointer it returns.
Summary
- A dynamic array stores a pointer, a size and a capacity.
- Grow it with
reallocinto a temporary pointer, doubling the capacity. - Use
memmoveto shift overlapping items when inserting or removing. - Free every inner allocation, then the array itself.
Next: Dynamic 2D Arrays in C.
