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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With