Is there a safe way to get the length of an array of function pointers?
Would the following work?
sizeof((uintptr_t)(*fp) / sizeof(uintptr_t)(*fp[0]))
Is there a safe way to get the length of an array of function pointers?
Would the following work?
sizeof((uintptr_t)(*fp) / sizeof(uintptr_t)(*fp[0]))
Regardless of element type, the standard idiom for the length of an array is:
#define countof(a) (sizeof(a) / sizeof(*(a)))
This will work only if a
is an actual array, i.e. declared as TYPE a[...]
. If a
is a pointer to TYPE
that was created from an array, such as by passing the array to the function, the above macro will produce an incorrect result.
I suspect your code is the result of such a confusion. It dereferences fp
, which is only correct if fp
is a pointer to the array, and not if it's a pointer to an array element.
Not a dynamically allocated array and not through a pointer to the array (which would by definition exclude dynamically allocated arrays).
sizeof(apointer)
will return the size of the pointer not the size of the buffer it points to. There is no way in C for sizeof
to know that the pointer points to an array or just a single element (which really is an array of 1).
If you do sizeof(*apointer)
it will return the size of a single element (or the first element in the array) because again, there is no way in C for sizeof to know that the pointer points to an array or just a single element.