2.2Dynamic Arrays
Growing the capacity
A dynamic array looks as if it can grow without limit, but inside it sits an ordinary fixed-size array. In this lesson you write by hand what happens when that array fills up: allocate a larger one, move the elements across and let the old one go.
- Which steps happen, and in which order, when you append to a full dynamic array
- Growing the array in C with
malloc, a copy loop andfree, and the same job in Java and Python - Why appending counts as O(1) on average even though an expensive copy happens now and then
1Idea
The structure holds three things: the address of the array that stores the elements (data), the number of stored elements (size) and the number of allocated slots (capacity). If size is less than the capacity, the new element goes straight into data[size].
If size equals the capacity, there is no room left. Four things happen: a new array twice as large is allocated, the old elements are copied into it in order, the old array is released with free, and data is updated to point to the new array. Then the append goes ahead as usual.
C also has realloc, which does all four in one call: realloc(d->data, newCapacity * sizeof(int)) tries to grow the block in place, and if it cannot, it allocates a new block, copies and frees the old one. Here we wrote the copy loop by hand so that every step is visible.
The starting capacity must be at least 1. If the capacity is 0, twice that is still 0 and the array never grows.
2Step by step
The drawing appends 50 to a full array with capacity 4. The top row is the old array, the bottom row the new one.
- Start.
datapoints to an array of four slots, all four in use.sizeis 4 andcapacityis 4. - We want to append 50. Since
size == capacity, there is no room; the array has to grow first. - A new array of 8 slots, twice the size, is allocated (malloc).
newDatapoints to it; its slots are still empty. - The loop copies the four old elements to the same indices. This step takes
sizesteps. - The old array is released with free,
datais moved to the new array andcapacitybecomes 8. - Now there is room. 50 is written into
data[4]andsizebecomes 5. The next three appends finish without copying.
struct DynamicArray { int* data; int size; // number of stored elements int capacity; // number of allocated slots}; bool append(struct DynamicArray* d, int value) { if (d->size == d->capacity) { // the array is full int newCapacity = d->capacity * 2; int* newData = malloc(newCapacity * sizeof(int)); if (newData == NULL) return false; for (int i = 0; i < d->size; i++) newData[i] = d->data[i]; // copy the old elements free(d->data); d->data = newData; d->capacity = newCapacity; } d->data[d->size] = value; d->size++; return true;}class DynamicArray { int[] data; int size = 0; // number of stored elements DynamicArray(int capacity) { data = new int[capacity]; } void append(int value) { if (size == data.length) { // the array is full int[] newData = new int[data.length * 2]; for (int i = 0; i < size; i++) newData[i] = data[i]; // copy the old elements data = newData; // the garbage collector frees the old array } data[size] = value; size++; }}class DynamicArray: def __init__(self, capacity=4): self.data = [None] * capacity self.size = 0 # number of stored elements def append(self, value): if self.size == len(self.data): # the array is full new_data = [None] * (len(self.data) * 2) for i in range(self.size): new_data[i] = self.data[i] # copy the old elements self.data = new_data self.data[self.size] = value self.size += 1The snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Most appends are a single write. Copying happens only when the array is full, and since the capacity doubles each time, it gets rarer and rarer. Over n appends starting from an empty array, the number of copied elements is 1 + 2 + 4 + ... < 2n; together with the n writes that is about 3n work. The share per append is constant. This is called amortized O(1).
While growing, the old and the new array are in memory together, so n slots of extra space are needed. The capacity is at most twice the size.
In the worst case a single append takes O(n): an element that arrives while the array is exactly full triggers a copy of every element. Appends are fast on average, but not every append is fast.
4Common mistake
The most common mistake with realloc is writing the result straight back into the same pointer:
d->data = realloc(d->data, newCapacity * sizeof(int));If realloc fails, it returns NULL but leaves the old block where it was. Because the result goes straight into d->data, the old block's address is lost: you can no longer reach the elements and the block stays behind as a leak. Store the result in a temporary variable first, and assign it to d->data only if it is not NULL. If you write the copy loop yourself, do not forget free(d->data); without it the old array stays in memory after every growth.
5Try it
You append 9 elements one after another to an empty dynamic array with capacity 4. How many times does it grow, and what is the final capacity?
The answer is B. When the 5th element arrives the array is full and the capacity goes from 4 to 8. When the 9th arrives, the 8 slots are full again and the capacity becomes 16.
Show the answer
The answer is B. When the 5th element arrives the array is full and the capacity goes from 4 to 8. When the 9th arrives, the 8 slots are full again and the capacity becomes 16.
If the capacity grew by 10 each time instead of doubling, how long would n appends take in total, starting from an empty array?
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.