Here is a macro for getting array size
#define array_size(array) \
(sizeof( array ) / (sizeof( array[0] ) * (sizeof( array ) != sizeof(void*) || sizeof( array[0] ) <= sizeof(void*)))
I think normally (sizeof( array ) / (sizeof( array[0] )) is good enough to get the size of the array.
I guess the part
(sizeof( array[0] ) * (sizeof( array ) != sizeof(void*) || sizeof( array[0] ) <= sizeof(void*))
is to avoid the whole thing divided by zero, anyone could help to explain?
Thanks in advance.
Cheers,
To determine the size of your array in bytes, you can use the sizeof operator: int a[17]; size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element.
Array size. The size of an array is the product of the lengths of all its dimensions. It represents the total number of elements currently contained in the array. For example, the following example declares a 2-dimensional array with four elements in each dimension.
To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows − type arrayName [ arraySize ]; This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type.
Multiplying sizeof array[0]
in the divisor by
(sizeof( array ) != sizeof(void*) || sizeof( array[0] ) <= sizeof(void*))
makes the divisor zero if
sizeof array == sizeof(void*)
and
sizeof array[0] > sizeof(void*)
In those cases, you get a division by zero during the compilation, which would cause the compilation to fail.
These checks are an attempt to detect arguments that are pointers (be they the result of array-to-pointer conversion or not), since one can't know how large an "array" a pointer points to by using that quotient.
It fails if other pointer types have different sizes than void*
, and it doesn't detect pointers to things that are not larger than void*
s. It probably does more harm than good by lulling the author in a false sense of security.
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