Is there a way to find how many values an array has? Detecting whether or not I've reached the end of an array would also work.
Basically, the length of an array is the total number of the elements which is contained by all the dimensions of that array. Property Value: This property returns the total number of elements in all the dimensions of the Array. It can also return zero if there are no elements in the array.
To get the size of a Java array, you use the length property. To get the size of an ArrayList, you use the size() method. Know the difference between the Java array length and the String's length() method.
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
.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With