简体   繁体   English

C:如何确定外部数组的sizeof(array)/ sizeof(struct)?

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

Defines the type x and an array X of that type. 定义类型x和该类型的数组X

xh: XH:

typedef struct _x {int p, q, r;} x;
extern x X[];

Separate file to keep the huge honking array X . 单独的文件保持巨大的鸣喇叭数组X

xc: XC:

#include "x.h"
x X[] = {/* lotsa stuff */};

Now I want to use X : 现在我想使用X

main.c: 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; main.c不会编译; the error is: 错误是:

error: invalid application of ‘sizeof’ to incomplete type ‘struct x[]’

How do I get the size of X without hardcoding it? 如何在没有硬编码的情况下获得X的大小?

In xh add: xh添加:

extern size_t x_count;

In xc add: xc添加:

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

Then use the variable x_count in your loop. 然后在循环中使用变量x_count

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 .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 .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 ;): 对于.c的定义,您甚至可以做得更好并使用静态断言( STATIC_ASSERT定义是作为读者的练习;):

x X[] = {LOTSA_STUFF};

STATIC_ASSERT(sizeof X != LOTSA_STUFF_SIZE, "oops, sizes are not equal");

You can't do that. 你不能这样做。 But you can provide a way to get the size. 但是你可以提供一种获得尺寸的方法。

In addition to 此外

extern x X[];

Add

extern size_t xArraySize;

or, preferably, 或者,最好是,

extern size_t xArraySize(void);

in xh xh

Define it in xc . xc定义它。

Change your loop to: 将你的循环改为:

for (i = 0; i < xArraySize(); i++)
    invert(X[i]);

If you simply include xh, the compiler has no idea what the real size of X is. 如果你只是包含xh,编译器不知道X的实际大小是多少。 Just by looking at xh, there is no way to guess. 只是看着xh,就没有办法猜测。 You have to declare X with a size: 您必须使用大小声明X:

extern x X[15];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM