>> The easiest way to get the length of a dynamic array is this
Is it? Forget about the 'array' part and look closely at the 'dynamic' part. A dynamic array is
not an array, it's a pointer to a block of memory that can be subscripted like an array:
#include <iostream>
#define length(x) (sizeof(x) / sizeof(*(x)))
void foo(int a[])
{
std::cout << "From foo(): " << length(a) << '\n';
}
int main()
{
int *a = new int[10];
int b[10];
std::cout << "From main(): " << length(a) << '\n';
foo(b);
}
So the sizeof trick just breaks silently when you use it on a dynamic array, or an array passed as a function parameter. Templates are a better solution because they complain when you pass a pointer and not an array:
#include <iostream>
template <typename T, int sz>
char (&array(T(&)[sz]))[sz];
void foo(int a[])
{
std::cout << "From foo(): " << sizeof array(a) << '\n';
}
int main()
{
int *a = new int[10];
int b[10];
std::cout << "From main(): " << sizeof array(a) << '\n';
foo(b);
}
The rule of thumb is that if you want the size of a dynamic array, you save it! If you want the size of an array parameter, you pass it! Anyone who doesn't know these rules or isn't comfortable with them would be better off using a smart container like std::vector or boost::array.