Get Array Size
Lesson outline
Fundamental Size Calculation
In C++, built-in (C-style) arrays have a fixed size that is part of their type and determined at compile time. To find the number of elements, a common method is to use the sizeof operator.
The total size of the array in bytes divided by the size of one element gives the element count.
Template-Based Size Calculation
Templates can preserve array size information when arrays are passed to functions, making it possible to calculate size reliably at compile time.
Standard Library Alternatives (C++17+)
Modern C++ introduces standard library utilities for safer size queries, avoiding manual calculations.
Multidimensional Arrays
sizeof yields the total size of the whole array object. Dividing by the size of the first subarray gives the first (outer) dimension; divide again to get the next dimension.
Common Pitfalls
| Scenario | Problem | Solution |
|---|---|---|
| Array passed to function | Array decays to pointer; sizeof returns pointer size | Pass size explicitly, or use templates / std::array / std::span (C++20) |
| Dynamic arrays | sizeof gives pointer size, not element count | Store size separately or use std::vector |
| Empty arrays (C-style) | Zero-length C-style arrays are not standard C++ (some compilers allow as an extension) | Use std::array or std::vector instead |
| Multidimensional arrays | sizeof alone gives total size; naïve division can be confusing | Use sizeof stepwise per dimension or helper templates |
Practical Example: Bounds-Safe Array Printing
Templates allow safe array printing by automatically deducing the number of elements at compile time, preventing buffer overruns.