There is no elegant or easy way, and even the sizeof
trick has limits; when an array expression is passed to a function, what the function receives is a pointer value, not an array. So something like
void foo(int a[])
{
size_t count = sizeof a / sizeof a[0];
...
}
won't work because in the context of a function parameter declaration, T a[]
and T a[N]
are identical to T *a
; a
is a pointer value, not an array, so you get the size of a pointer to int
divided by the size of the first element, which is not what you want.
Basically, you have to keep track of the array's size yourself. You know how big it is when you create it, so you have to preserve that information and pass it with the array:
void foo(int *a, size_t asize)
{
...
}
int main(void)
{
int arr[SOME_SIZE];
...
foo(arr, SOME_SIZE);
...
}