简体   繁体   English

C结构的大小

[英]size of C structure

struct st1{
    int a:1; int b:3; int c:6; int d:3;
}s1;

struct st2{
    char a:3;
}s2;

int main(){
    printf("%d : %d",sizeof(s1),sizeof(s2));
    getchar();
}    

I am getting the output as 2 : 1 我得到的输出为2:1

will you please tell me, how this program works and whats the use of : operator (a:1) here. 您能否告诉我该程序的工作原理以及:运算符(a:1)的用途是什么?

Thank you 谢谢

The : defines a bit-field . :定义位字段

In your example, objects of type struct st1 use 13 bits in some arrangement chosen by the compiler. 在您的示例中,类型struct st1对象以13位的方式由编译器选择。

The particular arrangement chosen when you compiled the code originated an object that occupies 2 bytes. 编译代码时选择的特定安排是产生一个占用2个字节的对象的。 The 13 bits are not necessarily the first (or last) in those bytes. 13个位不一定是这些字节中的第一个(或最后一个)。

The other struct type ( struct st2 ) occupies (3 bits out of) 1 byte. 其他结构类型( struct st2 )占用1个字节(占3位)。

The : operator used there specifies sizes in bits of the fields contained there. 此处使用的:运算符指定其中包含的字段的大小。 sizeof() return byte boundary length, so for the first, 13 bits (2 bytes), and for the second, 1 byte. sizeof()返回字节边界长度,因此对于前一个是13位(2个字节),对于第二个是1个字节。

There's at least two things worth noting here: 这里至少有两点值得注意:

  1. Every object must be addressable, which means it will at least occupy the size of one char. 每个对象都必须是可寻址的,这意味着它将至少占用一个字符的大小。
  2. The implementation is free to add padding for alignment or other issues as it sees fit. 该实现可以随意添加用于对齐或其他问题的填充。 Iow, a struct containing two ints is not guaranteed to be equal in size to sizeof(int)*2. 现在,不能保证包含两个int的结构的大小等于sizeof(int)* 2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM