C:如何确定外部阵列的sizeof(阵列)/的sizeof(结构)? [英] C: How to determine sizeof(array) / sizeof(struct) for external array?

查看:181
本文介绍了C:如何确定外部阵列的sizeof(阵列)/的sizeof(结构)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义类型 X 和阵列 X 该类型的。

Defines the type x and an array X of that type.

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 将无法编译;错误的是:

main.c won't compile; the error is:

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 在循环。

该司在包含数组初始化编译单元来完成,所以它知道整个数组的大小。

The division has to be done in the compilation unit that contains the array initializer, so it knows the size of the whole array.

这篇关于C:如何确定外部阵列的sizeof(阵列)/的sizeof(结构)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆