如何获取结构中的元素总数

Hir*_*dya 1 c struct

这是我的代码..

#include <stdio.h>

struct new {
    unsigned short b0 = 0;
    unsigned short b1 = 0;
    unsigned short b2 = 0;
    unsigned short b3 = 0;
    unsigned short b4 = 0;
    unsigned short b5 = 0;
    unsigned short b6 = 0;
    unsigned short b7 = 0;
};

int main()
{
    printf("Bit Field Example\n");
    struct new b; //Seems wrong to me
    int result = sizeof(b)/sizeof(*b); //Seems wrong to me
    printf("Size: %d\n", result);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我正在使用linux机器来编译提到的代码.我知道下面的行是错误的..

int result = sizeof(b)/sizeof(*b);
Run Code Online (Sandbox Code Playgroud)

但我不确定任何其他技术.首先,是否可以计算结构中元素的总数.请告诉我如何做到这一点.

提前致谢.

unw*_*ind 5

不可移植,一般或安全,不.

由于编译器可能会为对齐和其他原因添加填充,这会使大小增加,因此无法依赖正确的值.

如果元素的数量很重要,最好使用数组.

顺便说一句,这段代码:

int result = sizeof(b)/sizeof(*b);
Run Code Online (Sandbox Code Playgroud)

是错的,不会编译; b不是指针所以*b不是法律表达.你的意思是:

const int result = sizeof b / sizeof b.b0;
Run Code Online (Sandbox Code Playgroud)

另外,作为旁注,避免在C代码中使用C++关键字,这可能有些令人困惑.

更新我不明白你对"位字段"的引用.它们看起来像这样,并且只能出现在结构中:

struct strawberry {
  unsigned short fields : 10;
  unsigned short forever : 6;
};
Run Code Online (Sandbox Code Playgroud)

同样,它们不可能计算它们,因为它们甚至没有字节大小.但另一方面,你写了定义,包括每个字段的位宽,所以你应该知道有多少,对吧?