Edmund's blog

Writing code.

Getting the size of an array

How do you get the size of an array? This old fashioned method works.

1
2
3
4
5
6
7
#define COUNTOF(array) (sizeof(array) / sizeof(*array))

const char str1[] = "Hello";
size_t len1 = COUNTOF(str1);  // -> 6

const char *str2 = "Hello";  // BAD!
size_t len2 = COUNTOF(str2);  // -> 8

But if you don’t declare the array properly then things go horribly wrong. Never declare arrays as pointers!

The following C++ template function is much nicer. It does not compile at all when the array is declared as a pointer.

1
2
3
4
5
6
7
8
9
10
11
template<class T, size_t N>
size_t countof(const T (&)[N])
{
    return N;
}

const char str1[] = "Hello";
size_t len1 = countof(str1);  // -> 6

const char *str2 = "Hello";  // BAD!
size_t len2 = countof(str2);  // does not compile

The countof function takes a reference to an array and returns its size. It is a compile-time constant.