How do I find the length of an array?
As others have said, you can use the sizeof(arr)/sizeof(*arr)
, but this will give you the wrong answer for pointer types that aren't arrays.
template<class T, size_t N>
constexpr size_t size(T (&)[N]) { return N; }
This has the nice property of failing to compile for non-array types (Visual Studio has _countof
which does this). The constexpr
makes this a compile time expression so it doesn't have any drawbacks over the macro (at least none I know of).
You can also consider using std::array
from C++11, which exposes its length with no overhead over a native C array.
C++17 has std::size()
in the <iterator>
header which does the same and works for STL containers too (thanks to @Jon C).
Doing sizeof myArray
will get you the total number of bytes allocated for that array. You can then find out the number of elements in the array by dividing by the size of one element in the array: sizeof myArray[0]
So, you get something like:
size_t LengthOfArray = sizeof myArray / sizeof myArray[0];
Since sizeof
yields a size_t
, the result LengthOfArray
will also be of this type.
If you mean a C-style array, then you can do something like:
int a[7];
std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl;
This doesn't work on pointers (i.e. it won't work for either of the following):
int *p = new int[7];
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
or:
void func(int *p)
{
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
}
int a[7];
func(a);
In C++, if you want this kind of behavior, then you should be using a container class; probably std::vector
.
While this is an old question, it's worth updating the answer to C++17. In the standard library there is now the templated function std::size()
, which returns the number of elements in both a std container or a C-style array. For example:
#include <iterator>
uint32_t data[] = {10, 20, 30, 40};
auto dataSize = std::size(data);
// dataSize == 4