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

arrays, c, compiler-errors, sizeof

Solution

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.

Problem

Defines the type `x` and an array `X` of that type. x.h: ``` typedef struct _x {int p, q, r;} x; extern x X[]; ``` Separate file to keep the huge honking array `X`. x.c: ``` #include "x.h" x X[] = {/* lotsa stuff */}; ``` Now I want to use `X`: main.c: ``` #include "x.h" int main() { int i; for (i = 0; i < sizeof(X)/sizeof(x); i++) /* error here */ invert(X[i]); return 0; } ``` `main.c` won't compile; the error is: ``` error: invalid application of ‘sizeof’ to incomplete type ‘struct x[]’ ``` How do I get the size of `X` without hardcoding it?

Original source