I have a C++ array declared as mentioned below:
CString carray[] =
{
"A",
"B",
"C",
"D",
"E"
}
I want to determine the length of carray
at runtime. I am doing:
int iLength = sizeof(carray)/sizeof(CString);
Is this correct?
You can use the following function template. If you're using Boost, you can call boost::size
.
template <typename T, std::size_t N>
std::size_t size(T (&)[N])
{
return N;
}
int iLength = size(carray);
As others have already stated, however, you should prefer std::vector
to C-style arrays.
Yes. In case the declared element type ever changes, you could also write
int iLength = sizeof(carray)/sizeof(carray[0]);
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
}
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