结构中的位域位置

bitfields location in struct

假设有一些不相关的标志(sta_scansearch)被定义为结构中的位域,如下所示。声明这些标志的位置是否重要(就内存节省而言)?

struct sta_all {
    char name[16];
    unsigned int sta_scan:1;
    ...
    int interval;
    unsigned int search:1;
}

总的来说,是的。结构元素通常会以某种方式对齐(通常对齐元素的大小,偶尔会更大),混合各种大小会导致大量填充。有一些方法可以减轻这种情况。通常,如果您将所有相同大小的元素组合在一起,它们可能会在没有任何填充的情况下被打包。可以使用 pragma 来强制打包一个结构而不填充,但这将导致对结构成员的非对齐访问效率低下。

,但并非总是如此。


检查这个例子:

#include <stdio.h>
#include <string.h>

struct {
    char name[16];
    unsigned int sta_scan:1;
    int interval;
    unsigned int search:1;
} sta_all;

int main( ) {

   sta_all.interval = 4;
   printf( "Sizeof(sta_all) : %zu\n", sizeof(sta_all) );

   return 0;
}

输出:

Sizeof(sta_all) : 28

和:

#include <stdio.h>
#include <string.h>

struct {
    char name[16];
    unsigned int sta_scan:1;
    unsigned int search:1;
    int interval;
} sta_all;

int main( ) {

   sta_all.interval = 4;
   printf( "Sizeof(sta_all) : %zu\n", sizeof(sta_all) );

   return 0;
}

输出:

Sizeof(sta_all) : 24

发生这种情况是因为 填充on my platform

顺便说一句,如果你真的很追求内存效率,并且你可以接受访问速度的下降,那么你可以使用packing,因为link以上说明。

注意:上面的例子证实了 Jonathan Leffler mentioned in this :

Each of those bit-fields will probably be allocated as much space as the base type (unsigned int) and will use 1 of the 32 (16, 64, …) bits in that storage unit. If you decide to use bit-fields, you should make sure all the bit-fields are clustered together; it will minimize the space wasted. [...]. In the context of a structure, the compiler has no freedom to move the bitfields around.

..这与 linked 的答案非常吻合,因为编译器必须添加更少的 char gap_{i}[3];,当我们聚集位域时,从而最小化结构的大小!


值得吗?

没那么多恕我直言...:)