3

我有这三个结构,

typedef struct serial_header {
    int zigbeeMsgType;
    int seqNumber;
    int commandIdentifier;
    int dest;
    int src;
}serial_header_t;


typedef struct serial_packet {
  serial_header_t header;
  int data[];
} serial_packet_t;

最后一个是

typedef struct readAttributePacket
{
     int                     u8SourceEndPointId;
     int                     u8DestinationEndPointId;
     int                     u16ClusterId;
     int                     bDirectionIsServerToClient;
     int                     u8NumberOfAttributesInRequest;
     int                     bIsManufacturerSpecific;
     int                     u16ManufacturerCode;
     int                     pu16AttributeRequestList[];
}readAttributePacket_t;

我对这段代码感到不安,我只想将驻留在 serial_packet_t 中的 data[] 数组转换为 readAttributePacket_t 结构。我认为 data[] 应该是

data[]={0x01,0x01,0x04,0x02,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x01};

我需要将这些数据转换为 readAttributePacket_t 结构。但是下面的代码显示错误。

void main()
{
int a[]=  {0x32,0x00,0x31,0x69,0x69,0x00,0x00,0x01,0x01,0x04,0x02,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x01};
int i;
readAttributePacket_t *p;
serial_packet_t *data;

data = (serial_packet_t*)&a;

for(i=0;i<20;i++){
    printf(" %02x \n",a[i]);
}
p = (readAttributePacket_t *)&data->data;
printf("\nu8SourceEndPointId:%x \nu8DestinationEndPointId:%x \nu16ClusterId:%04x \nbDirectionIsServerToClient:%x \nu8NumberOfAttributesInRequest:%x \nbIsManufacturerSpecific:%x \nu16ManufacturerCode:%04x",p->u8SourceEndPointId,
    p->u8DestinationEndPointId,
    p->u16ClusterId,
    p->bDirectionIsServerToClient,
    p->u8NumberOfAttributesInRequest,
    p->bIsManufacturerSpecific,
    p->u16ManufacturerCode);


getch();
}

输出应该像

u8SourceEndPointId=01
u8DestinationEndPointId=01
u16ClusterId=0402
bDirectionIsServerToClient=00
u8NumberOfAttributesInRequest=02
bIsManufacturerSpecific=00
u16ManufacturerCode=0000

我怎样才能将 pu16AttributeRequestList[] 数组放入 readAttributePacket_t 结构中,应该这样,

pu16AttributeRequestList[0]=0000
pu16AttributeRequestList[1]=0001
4

2 回答 2

7

您不能只将数组转换为结构,因为它们只是不兼容的类型。由于内存对齐限制,编译器需要在结构的字段之间插入填充,因此成员不会位于您可能期望的内存地址。解决方案:

  1. 便携但手动操作更慢/更难(首选):手动将结构的字段复制到数组。
  2. 写得更短,但 GCC 特定:使用__attribute__((packed))关键字使 GCC 不会在结构字段之间引入填充。
于 2012-07-13T12:09:59.587 回答
0

构造 3 个结构的并集。全部在相同的内存空间上。那么你甚至不需要投射。

于 2012-07-13T12:37:23.330 回答