Loading lessons...
Getting the Array Size
Getting the Array Size
An array doesn't store its length for you to read, so C++ programmers compute it - with a small trick.
The sizeof trick
Every element in an array is the same size. So the total size divided by the size of one element gives you the count:
int nums[] = {10, 20, 30, 40, 50};
int len = sizeof(nums) / sizeof(nums[0]);
cout << len; // 5
sizeof(nums)- the total bytes of the whole array.sizeof(nums[0])- the bytes of a single element.- Dividing them gives the element count.
Modern C++: std::size
Since C++17 there's a cleaner, less error-prone helper:
#include <iterator>
std::size(nums); // 5
std::size says what you mean in one word and is safer to read.
One important catch
The trick works only when nums is still a real array. Pass it to a function and the name decays to a pointer - then sizeof(nums) measures the pointer, not the data. So only trust the trick in the same scope where the array was created.
TL;DR
sizeof(nums) / sizeof(nums[0])gives the number of elements.std::size(nums)(C++17) is the safer, cleaner version.- Both work only while the name is still a real array, not a pointer.
- Hardcoding sizes invites bugs - calculate the count instead.