Dynamic Array and std::vector
Grow contiguous storage as values are appended.
What is Dynamic Array and std::vector?
A dynamic array keeps a logical size separate from allocated capacity and reallocates geometrically.
Important points
- State the invariants before implementing operations.
- Handle empty, full, and allocation-failure cases.
- Measure time complexity and memory ownership together.
See how it works
Press push_back repeatedly. When the array is full it allocates a block twice as big and copies everything across.
C and C++ code examples
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t size = 0, capacity = 2;
int *values = malloc(capacity * sizeof *values);
if (!values) return 1;
for (int value = 1; value <= 5; ++value) {
if (size == capacity) {
capacity *= 2;
int *grown = realloc(values, capacity * sizeof *values);
if (!grown) {
free(values);
return 1;
}
values = grown;
}
values[size++] = value * value;
}
printf("size=%zu capacity=%zu last=%d\n",
size, capacity, values[size - 1]);
free(values);
}
size=5 capacity=8 last=25
#include <iostream>
#include <vector>
int main() {
std::vector<int> values;
for (int value = 1; value <= 5; ++value) {
values.push_back(value * value);
}
std::cout << "size=" << values.size()
<< " last=" << values.back() << '\n';
}
size=5 last=25
C and C++ comparison
The C version explicitly checks realloc and updates capacity. std::vector packages the same growth strategy with automatic destruction, iterators, and exception safety.
Structures and operations are usually separate and allocation is explicit.
Classes and containers can preserve invariants and manage resources automatically.
Practice exercises
Run both versions, then modify them to observe the different language guarantees.
- Add empty and capacity-boundary tests.
- Implement cleanup and verify no leaks remain.
- Compare operation complexity with a standard container.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Rotate Array Rotate a list to the right by some steps. Easy
- Growing a Dynamic Array Simulate how a dynamic array doubles its capacity and count the reallocations and copied elements. Easy