定义类型 x
和该类型的数组 X
。
x.h:
typedef struct _x {int p, q, r;} x;
extern x X[];
单独的文件来保存巨大的喇叭数组X
。
x.c:
#include "x.h"
x X[] = {/* lotsa stuff */};
现在我想使用X
:
主.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
不会编译;错误是:
error: invalid application of ‘sizeof’ to incomplete type ‘struct x[]’
如何在不硬编码的情况下获取 X
的大小?
最佳答案
在x.h
中添加:
extern size_t x_count;
在x.c
中添加:
size_t x_count = sizeof(X)/sizeof(x);
然后在循环中使用变量 x_count
。
除法必须在包含数组初始值设定项的编译单元中完成,因此它知道整个数组的大小。
关于C: 如何确定外部数组的 sizeof(array)/sizeof(struct)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23230114/