How to know the size of a const array?

arrays, c, c++, sizeof

Solution

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;
}

Problem

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?

Original source