C++20 sections · 1024 units
Open in Course

Dynamic Arrays

Variable-sized allocation

Dynamic arrays let you choose size at runtime. Write int* arr = new int[n]; where n is a variable. Stack arrays in standard C++ require constant sizes known at compile time. Access elements normally: arr[0], arr[1], etc.

The pointer arithmetic works just like with stack arrays. But you're responsible for tracking the size since the array doesn't know it. Always delete[] when done, even if an exception might occur.

Better yet, use std::vector which handles all of this automatically with the same performance.