gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:46:35 26 4
gpt4 key购买 nike

定义类型 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com