1

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]))
Shmil The Cat
  • 4,548
  • 2
  • 28
  • 37
nwmcsween
  • 361
  • 2
  • 12
  • 1
    At least it wouldn't work as you intend. Keep an eye on your parentheses. And please show the declaration of `fp`. – moooeeeep Mar 13 '13 at 19:35

2 Answers2

3

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.

user4815162342
  • 141,790
  • 18
  • 296
  • 355
1

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.

Dave Rager
  • 8,002
  • 3
  • 33
  • 52