Assuming that by array, you are talking about traditionnal C style array like this one:
int anArray[25];
If you don't need compile-time value, then the following function will be able to evaluate the number of items in any array.
template <typename T, int n> int len(T(&array)[n])
{
return (sizeof(array)/ sizeof(array[0]));
}
You can then get the length like that:
int n = len(anArray);
Since that code will only compile for arrays and not pointers, the template is safer to uses as it would not compile with pointers (or the equivalent
int not_really_an_array[]
).
Also, in the Template function, one could simply write
return n;
but I have copied the original code (including all superfluous parenthesis) to make it clear that I do same thing.