That is, the number of elements the array can hold?
Best Answer
Executive summary:
int a[17];
size_t n = sizeof(a)/sizeof(a[0]);
Full answer:
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.
You could do this with the type, like this:
int a[17];
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
the sizeof(int) as well.
So the preferred divisor is sizeof(a[0]) or the equivalent sizeof(*a), the size of the first element of the array.
int a[17];
size_t n = sizeof(a) / sizeof(a[0]);
Another advantage is that you can now easily parameterize
the array name in a macro and get:
#define NELEMS(x) (sizeof(x) / sizeof((x)[0]))
int a[17];
size_t n = NELEMS(a);
If the array is a global, static, or automatic variable (int array[10];), then sizeof(array)/sizeof(array[0]) works.
If it is a dynamically allocated array (int* array = malloc(sizeof(int)*10);) or passed as a function argument (void f(int array[])), then you cannot find its size at run-time. You will have to store the size somewhere.
Note that sizeof(array)/sizeof(array[0]) compiles just fine even for the second case, but it will silently produce the wrong result.
C arrays don't store their own sizes anywhere, so sizeof only works the way you expect if the size is known at compile time. malloc() is treated by the compiler as any other function, so sizeof can't tell that arr points to the first element of an array, let alone how big it is. If you need to know the size of the array, you need to explicitly pass it to your function, either as a separate argument, or by using a struct containing a pointer to your array and its size.
Best Answer
Executive summary:
Full answer:
To determine the size of your array in bytes, you can use the
sizeof
operator: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:
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 thesizeof(int)
as well.So the preferred divisor is
sizeof(a[0])
or the equivalentsizeof(*a)
, the size of the first element of the array.Another advantage is that you can now easily parameterize the array name in a macro and get: