C: How to determine sizeof(array) / sizeof(struct) for external array? C: How to determine sizeof(array) / sizeof(struct) for external array? arrays arrays

C: How to determine sizeof(array) / sizeof(struct) for external array?


In x.h add:

extern size_t x_count;

In x.c add:

size_t x_count = sizeof(X)/sizeof(x);

Then use the variable x_count in your loop.

The division has to be done in the compilation unit that contains the array initializer, so it knows the size of the whole array.


If it is possible to place a termination indicator at the end of the array, such as:

x X[] = {/* lotsa stuff */, NULL};

It might be that the number of elements in the array would be irrelevant:

#include "x.h"int main()   {   x *ptr = X;   while(ptr)      invert(ptr++);   return 0;   }

If the number of elements in the array is needed, the above method can be also be used to count the elements.


Here a solution using compound literals:

in .h

typedef struct _x {int p, q, r} x;#define LOTSA_STUFF        {1, 2, 3}, {4, 5, 7}#define LOTSA_STUFF_SIZE  sizeof ((x[]) {LOTSA_STUFF})extern x X[LOTSA_STUFF_SIZE];

and in .c

x X[LOTSA_STUFF_SIZE] = {LOTSA_STUFF};

For the definition in .c, you can even do better and use a static assert (definition of the STATIC_ASSERT is let as an exercise for the reader ;):

x X[] = {LOTSA_STUFF};STATIC_ASSERT(sizeof X != LOTSA_STUFF_SIZE, "oops, sizes are not equal");