Posted By: Mark Harrison
How do I determine the size of my array in C?
That is, the number of elements the array can hold?
int a; size_t n = sizeof(a)/sizeof(a);
To determine the size of your array in bytes, you can use the
int a; 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.
You could do this with the type, like this:
int a; size_t n = sizeof(a) / sizeof(int);
and get the proper answer (68 / 4 = 17), but if the type of
a changed you would have a nasty bug if you forgot to change
sizeof(int) as well.
So the preferred divisor is
sizeof(a) or the equivalent
sizeof(*a), the size of the first element of the array.
int a; size_t n = sizeof(a) / sizeof(a);
Another advantage is that you can now easily parameterize
the array name in a macro and get:
#define NELEMS(x) (sizeof(x) / sizeof((x))) int a; size_t n = NELEMS(a);