I've seen several macros for array length floating around:
From this question:
#define length(array) (sizeof(array)/sizeof(*(array)))
#define ARRAY_LENGTH(array) (sizeof((array))/sizeof((array)[0]))
#define SIZE(array, type) (sizeof(array) / (sizeof(type))
And Visual Studio's _countof
:
#define _countof(_Array) (sizeof(_Array) / sizeof(_Array[0]))
What I'd like to know is:
array[0]
and *array
?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.
Arrays are static so you won't be able to change it's size. You'll need to create the linked list data structure. The list can grow and shrink on demand.
Token-pasting operator (##) The '##' pre-processing operator performs token pasting. When a macro is expanded, the two tokens on either side of each '##' operator are combined into a single token, which then replaces the '##' and the two original tokens in the macro expansion.
We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);
Here's a better C version (from Google's Chromium project):
#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
It improves on the array[0]
or *array
version by using 0[array]
, which is equivalent to array[0]
on plain arrays, but will fail to compile if array
happens to be a C++ type that overloads operator[]()
.
The division causes a divide-by-zero operation (that should be caught at compile time since it's a compile-time constant expression) for many (but not all) situations where a pointer is passed as the array
parameter.
See Is there a standard function in C that would return the length of an array? for more details.
There's a better option for C++ code. See Compile time sizeof_array without using a macro for details.
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