加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:33:51 所属栏目:百科 来源:网络整理
导读:定义类型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: main.c中: #include "x.h"int main(){ int i; for (i = 0; i sizeof(X
定义类型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:

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不会编译;错误是:

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.

必须在包含数组初始化器的编译单元中进行分割,所以它知道整个数组的大小.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读