I have a C++ array declared as mentioned below:
CString carray[] =
{
\"A\",
\"B\",
\"C\",
\"D\",
\"E\"
}
Yes. In case the declared element type ever changes, you could also write
int iLength = sizeof(carray)/sizeof(carray[0]);
This code is correct but in most circumstances there are better ways to handle arrays in C++. Especially since this method won't work with dynamically sized arrays.
For such cases, use the standard library class std::vector
that represents an array of dynamic size (i.e. you can insert and remove entries).
That is correct, as it is using metaprogramming as this:
template <typename T, std::size_t N>
inline std::size_t array_size( T (&)[N] ) {
return N;
};
You must know that this works when the compiler is seeing the array definition, but not after it has been passed to a function (where it decays into a pointer):
void f( int array[] )
{
//std::cout << array_size( array ) << std::endl; // fails, at this point array is a pointer
std::cout << sizeof(array)/sizeof(array[0]) << std::endl; // fails: sizeof(int*)/sizeof(int)
}
int main()
{
int array[] = { 1, 2, 3, 4, 5 };
f( array );
std::cout << array_size( array ) << std::endl; // 5
std::cout << sizeof(array)/sizeof(array[0]) << std::endl; // 5
}
That's not runtime, it's compile time. The way you're using is correct. Note that Visual Studio defines a _countof
function that does the same.
At runtime, the length cannot be determined. You either keep a length yourself, or use std::vector