There are 3 possibilities to determine array size in my mind:
The array is declared as array. The sizeof
operator can be used. (Nice, it's comile-time resolved.)
The array is passed as pointer. The size cannot be determined from type. It has to be provided another way.
The array length can be determined by its contents. This is used for C strings but can be used for other types also. (Consider, that the end-marker consumes an element itself. Thus, the maximum length is one less than the capacity.)
Sample code test-array-size.c
:
#include <stdio.h>
/* an array */
static int a[5] = { 0, 0, 0, 0, -1 };
/* a function */
void func(int a1[], int len1, int *a2)
{
/* size of a1 is passed as len1 */
printf("a1 has %d elements.\n", len1);
/* len of a2 is determined with end marker */
int len2;
for (len2 = 0; a2[len2] >= 0; ++len2);
printf("a2 has (at least) %d elements.\n", len2 + 1);
}
/* HOW IT DOES NOT WORK: */
void badFunc(int a3[5])
{
int len = sizeof a3 / sizeof a3[0]; /* number of elements */
printf("a3 seems to have %d elements.\n", len);
}
/* the main function */
int main()
{
/* length of a can be determined by sizeof */
int size = sizeof a; /* size in bytes */
int len = sizeof a / sizeof a[0]; /* number of elements */
printf("a has %d elements (consuming %d bytes).\n", len, size);
/* Because this is compile-time computable it can be even used for
* constants:
*/
enum { Len = sizeof a / sizeof a[0] };
func(a, Len, a);
badFunc(a);
/* done */
return 0;
}
Sample session:
$ gcc -std=c11 -o test-array-size test-array-size.c
test-array-size.c: In function 'badFunc':
test-array-size.c:19:20: warning: 'sizeof' on array function parameter 'a3' will return size of 'int *' [-Wsizeof-array-argument]
int len = sizeof a3 / sizeof a3[0]; /* number of elements */
^
test-array-size.c:17:18: note: declared here
void badFunc(int a3[5])
^
$ ./test-array-size.exe
a has 5 elements (consuming 20 bytes).
a1 has 5 elements.
a2 has (at least) 5 elements.
a3 seems to have 1 elements.
$