A classic macro to compute the number of elements in an array is this:
#define countof(a) (sizeof(a) / sizeof(*(a)))
The problem with this is it fails silently if the argument is a pointer instead of an array. Is there a portable way to ensure this macro is only used with an actual array by generating a compile time error if a
is not an array?
EDIT: my question seems to be a duplicate of this one: Array-size macro that rejects pointers
To count the occurrences of each element in an array: Declare a variable that stores an empty object. Use the for...of loop to iterate over the array. On each iteration, increment the count for the current element if it exists or initialize the count to 1 .
Just divide the number of allocated bytes by the number of bytes of the array's data type using sizeof() . int numArrElements = sizeof(myArray) / sizeof(int);
Using a non-portable built-in function, here is a macro to perform a static assertion that a
is an array:
#define assert_array(a) \
(sizeof(char[1 - 2 * __builtin_types_compatible_p(typeof(a), typeof(&(a)[0]))]) - 1)
It works with both gcc
and clang
. I use it to make the countof()
macro safer:
#define countof(a) (sizeof(a) / sizeof(*(a)) + assert_array(a))
But I don't have a portable solution for this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With