Data Structures in C/C++

Dynamic Array in C and std::vector in C++

How does a vector grow without copying on every push? Learn size, capacity and doubling with realloc.

  • Intermediate
  • 4 min read
  • 2 runnable examples
What you'll learn
  • Size versus capacity
  • Growing with realloc in C
  • What std::vector does for you
After pushing 1, 4, 9, 16, 25
1[0]
4[1]
9[2]
16[3]
25[4]
·[5]
·[6]
·[7]
size = 5, capacity = 8: three more pushes fit before the next reallocation.

Size, capacity and growth

The problem

You often do not know how many items you will store: lines in a file, players joining a game. A fixed array is either too small or wastes memory. A dynamic array grows as needed while keeping elements side by side.

Think of it like this

A dynamic array is like a family that moves to a bigger house when the old one fills up. Instead of adding one room at a time, they move to a house twice as big, so they do not have to move again soon.

From moving house to code
size👪 How many people live here
capacity🏠 How many rooms the house has
capacity *= 2;🚚 Move to a house twice as big
realloc(values, ...)📦 Pack and move everything over
Grow by doubling so adding stays fast on average.
In one sentence

A dynamic array stores elements in one block of memory and moves them to a block twice as big when it fills up. std::vector is C++'s dynamic array.

Important points

  1. size counts stored values and capacity counts allocated slots.
  2. When size == capacity, the capacity doubles and realloc moves the data to a bigger block.
  3. The result of realloc goes into grown first, so the old block is not lost if it fails.
  4. push_back on std::vector does all of this automatically.

When to use it

  • Collections whose size is unknown in advance.
  • Reading data until the end of input.
  • The default container in C++ (std::vector).

When not to use it

  • Frequent insertion at the front: every element must shift.
  • Keeping pointers to elements while adding: growth moves them and the pointers become invalid.

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

C
Run code →
main.c
#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);
}
Get a Run button for this example Result of running the code
size=5 capacity=8 last=25
C++
Run code →
main.cpp
#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';
}
Get a Run button for this example Result of running the code
size=5 last=25

C and C++ comparison

The array starts with room for 2 values. Each time it is full, capacity doubles to 4 and then 8, and realloc moves the values to the bigger block. After adding five squares, size is 5, capacity is 8 and the last value is 25.

C

Structures and operations are usually separate and allocation is explicit.

C++

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.

Common mistakes

Assigning realloc's result directly

If realloc fails it returns NULL and the original block is leaked.

Problem
values = realloc(values, capacity * sizeof *values);
Fix
int *grown = realloc(values, capacity * sizeof *values);
if (!grown) { free(values); return 1; }
values = grown;

Growing by one slot at a time

Reallocating on every push copies the data again and again.

Problem
capacity += 1;
Fix
capacity *= 2;

Finished this lesson?

Mark it as learned to track your progress.

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.

All challenges