Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 658
Yimin Rong Avatar asked Apr 22 '14 21:04

Yimin Rong


2 Answers

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.

like image 136
Barmar Avatar answered Nov 15 '22 19:11

Barmar


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.

like image 33
Mahonri Moriancumer Avatar answered Nov 15 '22 18:11

Mahonri Moriancumer