How to use structure with dynamically changing size of data?

后端 未结 3 1874
青春惊慌失措
青春惊慌失措 2021-01-27 06:38

Question for C only, C++ and vectors do not solve problem.

I have such structure:

typedef __packed struct Packet_s
{
  U8  head;
  U16 len;
  U32 id;
  U         


        
3条回答
  •  萌比男神i
    2021-01-27 07:16

    You can't have dynamic buffer in middle of a struct.

    Another way to solve the problem is divide the struct to two pieces. For example (notice that data is here a flexible array member):

    typedef __packed struct Packet_s
    {
      U8  head;
      U16 len;
      U32 id;
      U8  data[];
    } Packet_t, *Packet_p;
    
    typedef __packed struct PacketEnd_s
    {
      U8  end;
      U16 crc;
    } PacketEnd_t, *PacketEnd_p;
    

    Then use

    Packet_t *pPacket = (Packet_t *)&Buffer;
    PacketEnd_t *pPacketEnd = (PacketEnd_t *)( count pointer here by using pPacket->len );
    

    Assuming that __packed allows to use unaligned access to members of __packed structs.

提交回复
热议问题