Reputation: 751
given the following code:
const myStr codesArr[] = {"AA","BB", "CC"};
myStr is a class the wraps char*
.
I need to loop over all the items in the array but i don't know the number of items.
I don't want to define a const
value that will represent the size (in this case 3)
Is it safe to use something like:
const int size = sizeof(codesArr) / sizeof(myStr);
what to do?
Upvotes: 18
Views: 23632
Reputation: 157314
The safe and clear way to do this is to use std::extent
(since C++11):
const size_t size = std::extent<decltype(codesArr)>::value;
Upvotes: 38
Reputation: 31952
The best way(pre c++11) to get size of an array is given at this link. It is a convoluted template trick, but has many advantages over other approaches as is discussed in the above link. The method is to use the following macro+function:
template <typename T, size_t N>
char ( &_ArraySizeHelper( T (&array)[N] ))[N];
#define countof( array ) (sizeof( _ArraySizeHelper( array ) ))
Its advantages, among others, are that it is purely a compile time operation, which is better than doing it in run time, and , before c++11's constexpr, is the only method that allows you to use the result of the operation as the size of another array ( since its a compile time constant
Upvotes: 1
Reputation: 258548
You can use int size = sizeof(codesArr) / sizeof(myStr);
as long as you don't pass it as parameter to a function, because then the array will decay into a pointer and lose size information.
You can also use a template trick:
template<typename T, int sz>
int size(T(&)[sz])
{
return sz;
}
Upvotes: 19