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.
For old g++ compiler, you can do this
template <class T, size_t N>
char (&helper(T (&)[N]))[N];
#define arraysize(array) (sizeof(helper(array)))
int main() {
int a[10];
std::cout << arraysize(a) << std::endl;
return 0;
}
I personally would suggest (if you are unable to work with specialized functions for whatever reason) to first expand the arrays type compatibility past what you would normally use it as (if you were storing values ≥ 0:
unsigned int x[] -> int x[]
than you would make the array 1 element bigger than you need to make it. For the last element you would put some type that is included in the expanded type specifier but that you wouldn't normally use e.g. using the previous example the last element would be -1. This enables you (by using a for loop) to find the last element of an array.
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] )
For C++/CX (when writing e.g. UWP apps using C++ in Visual Studio) we can find the number of values in an array by simply using the size()
function.
Source Code:
string myArray[] = { "Example1", "Example2", "Example3", "Example4" };
int size_of_array=size(myArray);
If you cout
the size_of_array
the output will be:
>>> 4
A good solution that uses generics:
template <typename T,unsigned S>
inline unsigned arraysize(const T (&v)[S]) { return S; }
Then simply call arraysize(_Array);
to get the length of the array.
Source
Is there a way to find how many values an array has?
Yes!
Try sizeof(array)/sizeof(array[0])
Detecting whether or not I've reached the end of an array would also work.
I dont see any way for this unless your array is an array of characters (i.e string).
P.S : In C++ always use std::vector
. There are several inbuilt functions and an extended functionality.