定义一个通信数据帧结构体,如下所示‘
1 struct stru_io_frame_head 2 { 3 uint8_t fir68; 4 uint8_t meter_id[6]; 5 uint8_t scd68; 6 uint8_t frame_c; 7 uint8_t frame_l; 8 uint8_t di[2]; 9 uint8_t data[1]; 10 };
如何求结构体成员的偏移地址?最近阅读程序看到一种新的方式,定义一个宏,如下所示:
1 #define offset_of(obj_type,mb) ((uint16_t)&(((obj_type*)0)->mb))
如果需要求fram_l的偏移地址,那么可以使用语句:
offset_of(struct stru_io_frame_head, frame_l),其值为9,
分析:(struct stru_io_frame_head *)0->frame_l, 定义一个地址为0的结构体指针并访问其成员变量frame_l,然后&((struct stru_io_frame_head *)0->frame_l)取得该成员变量的地址,相对于0地址,frame_l的偏移为9,故改地址为9。如果把0换成10,结果为19。
下列为测试程序:
1 #include <stdio.h> 2 #include "protocol.h" 3 #include "userdef.h" 4 5 #define offset_of(obj_type,mb) ((uint16_t)&(((obj_type*)0)->mb)) 6 struct stru_io_frame_head 7 { 8 uint8_t fir68; 9 uint8_t meter_id[6]; 10 uint8_t scd68; 11 uint8_t frame_c; 12 uint8_t frame_l; 13 uint8_t di[2]; 14 uint8_t data[1]; 15 }; 16 17 18 int main(int argc, char *argv[]) 19 { 20 uint8_t buffer1[]={0xFE,0xFE,0x68,0x01,0x00,0x00,0x00,0x00,0x00,0x68,0x00,0x02,0x35,0x35,0x3D,0x16}; 21 uint8_t length=sizeof(buffer1); 22 uint16_t s; 23 uint16_t x1,x2,x3,x4,x5,x6,x7; 24 s=sizeof(struct stru_io_frame_head); 25 printf("size=%d ",s); 26 x1 = offset_of(struct stru_io_frame_head, fir68); 27 x2 = offset_of(struct stru_io_frame_head, meter_id[0]); 28 x3 = offset_of(struct stru_io_frame_head, scd68); 29 x4 = offset_of(struct stru_io_frame_head, frame_c); 30 x5 = offset_of(struct stru_io_frame_head, frame_l); 31 x6 = offset_of(struct stru_io_frame_head, di[0]); 32 x7 = offset_of(struct stru_io_frame_head, data[0]); 33 34 printf("it is %d,%d,%d,%d,%d,%d,%d ",x1,x2,x3,x4,x5,x6,x7); 35 printf("Hello C-Free! "); 36 return 0; 37 }
其输出结果为:
size=13
it is 0,1,7,8,9,10,12
Hello C-Free!
请按任意键继续. . .