[英]structure offset with bit field
I have a question on getting the index offset to a field in the structure, below is the code I use to test: 我有一个关于使索引偏移到结构中的字段的问题,下面是我用来测试的代码:
#include <stdio.h>
typedef struct ipv4_pkt_struct
{
/*ethernet hdr*/
unsigned char DestMacAddr[6] ;
unsigned char SrcMacAddr[6] ;
unsigned char EthernetType[2] ;
/*IP hdr*/
unsigned char Version :4;
unsigned char IHL :4;
unsigned char TypeofService[2] ;
unsigned char Total_Length[4] ;
} ipv4_pkt_struct_t;
int main()
{
ipv4_pkt_struct_t A;
printf ("%d\n",(unsigned char*)A.TypeofService - (unsigned char*)A.DestMacAddr) ;
printf("Hello World");
return 0;
}
The output is: 输出为:
15
Hello World
which is correct, but however if I do something like: 正确,但是如果我做类似的事情:
printf ("%d\n",(unsigned char*)A.IHL - (unsigned char*)A.DestMacAddr) ;
It will give me a very wired output: 它会给我非常有线的输出:
1296908304
Hello World
and 和
printf ("%d\n",(unsigned char*)&A.IHL - (unsigned char*)A.DestMacAddr) ;
give an compile error: 给出一个编译错误:
main.c: In function 'main':
main.c:29:5: error: cannot take address of bit-field 'IHL'
printf ("%d\n",(unsigned char*)&A.IHL - (unsigned char*)A.DestMacAddr) ;
how can I get the correct offset ? 如何获得正确的偏移量?
In C bit field members are not addressable. 在C位字段中,成员不可寻址。
n1570-§6.5.3.2 (p1): n1570-§6.5.3.2(p1):
The operand of the unary
&
operator shall be either a function designator, the result of a[]
or unary*
operator, or an lvalue that designates an object that is not a bit-field [...]一元
&
运算符的操作数应为函数指定符,[]
或一元*
运算符的结果,或者是指定不是位字段的对象的左值[...]
Apart from that the line 除了那条线
printf ("%d\n",(unsigned char*)A.TypeofService - (unsigned char*)A.DestMacAddr) ;
should be 应该
printf ("%td\n", A.TypeofService - A.DestMacAddr) ;
You are casting an (uninitialized) unsigned char to a pointer; 您正在将(未初始化的)无符号字符转换为指针; besides that accessing uninitialized data is undefined behaviour, even if you initialize it, you calculate with values and not with the addresses where these values reside.
除了访问未初始化的数据是未定义的行为外,即使您将其初始化,也要使用值而不是使用这些值所在的地址进行计算。
I'd suggest to use offsetof , which is build for exactly your usecase. 我建议使用offsetof ,它是为您的用例而构建的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.