The short answer is "no"; in C, there is no way to get the number of elements in an array based on the array expression alone. The sizeof
trick is about as good as it gets, and its use is limited to expressions of array type. So the following won't work:
char *foo = malloc(1024);
size_t count = sizeof foo;
count
receives the number of bytes for the pointer type (4 on a typical desktop architecture), not in the allocated block.
char arr[100];
char *p = arr;
size_t count = sizeof p;
Same as above.
void foo(char *arr)
{
size_t count = sizeof arr; // same as above
...
}
void bar(void)
{
char array[100];
foo(array);
...
}
Same as above.
If you need to know how many elements are in an array, you need to track that information separately.
C's treatment of arrays is the source of a lot of heartburn.