奇怪的结构定义?

时间:2012-07-20 09:34:28

标签: c struct

  

可能重复:
  What does 'unsigned temp:3' means

struct的定义是这样的,

typedef struct
{   
    uint32_t length : 8;  
    uint32_t offset : 24;
    uint32_t type : 8;
} A;

我之前没有见过这种定义,:8:24是什么意思?

3 个答案:

答案 0 :(得分:6)

它定义了位域。这告诉编译器length是8位,offset是24位,type也是8位。

答案 1 :(得分:3)

请参阅以下链接。它们是位域。 http://www.cs.cf.ac.uk/Dave/C/node13.html {
{3}}

#include <stdio.h>

typedef unsigned int uint32_t;

#pragma pack(push, 1)
typedef struct
{
    uint32_t length : 8;
    uint32_t offset : 24;
    uint32_t type : 8;
} A;

typedef struct
{
    uint32_t length;
    uint32_t offset;
    uint32_t type;
} B;
#pragma pack(pop)

int main()
{
  printf("\n Size of Struct: A:%d   B:%d", sizeof(A), sizeof(B));
  return 0;
}

结构A的大小为5个字节,其中B的大小为12个字节。

答案 2 :(得分:1)

这种表示法定义了位字段,即该结构变量的位数大小。

相关问题