I have a C++ array declared as mentioned below:
CString carray[] =
{
\"A\",
\"B\",
\"C\",
\"D\",
\"E\"
}
The best way is to use a macro and use that where ever you want the size.
#define MAX_ROWS 1048
int array[MAX_ROWS];
This way you can use the MAX_ROWS even in a function where the array is passed as an argument.
Windows SDK (i.e. windows.h header) offers the macro ARRAYSIZE which implements this functionality in a safe manner(i.e. doesn't work with non-static arrays)
Read this article by Ivan J. Johnson in Dr. Dobbs Journal. I think it covers most of the solutions presented here. It also outlines the merits and demerits of each approach very nicely.
Yes, this is the correct way to do it, but it will only work in this situation where the size of array is known at compile time and is seen at the site of the sizeof( array )
statement. It will not work with dynamically sized arrays - you will need other methods for them like using a container like stl::vector or passing/storing the number of elements as a separate parameter.
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.
If you have a dynamic array, you should probably use something like an STL vector. http://www.cppreference.com/wiki/stl/vector/start
Normal arrays in C++ are fixed size and you need to manually allocate memory to expand dynamic ones.
If you know your array size at compile time, use a constant rather than a calculation.