</>EmbeddedInterview

How do you find the number of elements in an array?

EasyPointers & Memory

Short answer: Divide the size of the whole array by the size of one element: sizeof(a) / sizeof((a)[0]), usually wrapped in an ARRAY_SIZE macro. It only works on a real array whose declaration is in scope; on a pointer (including an array passed to a function) it silently gives a wrong result.

#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))

static const uint16_t baud_table[] = { 9600, 19200, 38400, 57600 };

for (size_t i = 0; i < ARRAY_SIZE(baud_table); i++) { /* 4 iterations */ }

void f(const uint16_t *t)
{
    size_t n = ARRAY_SIZE(t);    /* WRONG: sizeof(pointer) / sizeof(uint16_t) = 2 on 32-bit */
}

Making it safe (GCC/Clang): the Linux kernel's version fails to compile when given a pointer:

#define __must_be_array(a) \
    (sizeof(struct { int : -!!(__builtin_types_compatible_p(__typeof__(a), __typeof__(&(a)[0]))); }))
#define ARRAY_SIZE_SAFE(a) (sizeof(a) / sizeof((a)[0]) + __must_be_array(a))

C23 and C++17 make this easier: C++ has std::size(a), which refuses pointers.

Why (a)[0] and not *a: both work for arrays; the brackets are just a common idiom. The parentheses around a protect expressions passed to the macro.

Best practice for functions: always pass the element count with the pointer (void send(const uint8_t *buf, size_t len)), or pass a struct that contains both.

Static check for tables that must match an enum:

enum mode { MODE_IDLE, MODE_RUN, MODE_COUNT };
static const char *const mode_name[] = { "idle", "run" };
_Static_assert(ARRAY_SIZE(mode_name) == MODE_COUNT, "mode_name out of sync with enum mode");