我想在 Visual C++ 中使用这个结构:
struct iphdr
{
unsigned int ihl:4;
unsigned int version:4;
u_int8_t tos;
u_int16_t tot_len;
u_int16_t id;
u_int16_t frag_off;
u_int8_t ttl;
u_int8_t protocol;
u_int16_t check;
struct in_addr ip_src;
struct in_addr ip_dst;
};
但是在调试时我发现sizeof(struct iphdr) = 24
,它应该是20
奇怪的是,当我用 char
替换 ihl
和 version
时,sizeof(struct iphdr) = 20
最佳答案
位域 ihl
和 version
将被放置在 unsigned int
字段中(尽管它们适合一个字符)。因此,由于填充,字段 tos
将放置在偏移量 4 处,而 tot_length
将放置在偏移量 6 处。
关于c++ - Visual C++ 中的位域问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9553633/