我们可以使用链接中指定的零长度数组初始化结构:
零长度。
我正在使用以下结构:
typedef unsigned char UINT8;
typedef unsigned short UINT16;
typedef struct _CommandHeader
{
UINT16 len;
UINT8 payload[0];
} CommandHeader;
typedef struct _CmdXHeader
{
UINT8 len;
UINT8 payload[0];
} CmdXhHeader;
现在 CommandHeader.payload 应该指向/包含 CmdXHeader 结构。即内存应该是这样的:
-------------------------------------------------------------
| CommandHeader.len | CmdXHeader.len | CmdXHeader.payload ....|
-------------------------------------------------------------
我可以轻松地将 CmdXHeader / CommandHeader 分配到自定义长度。但是如何为 CmdXHeader 有效负载赋值或如何将 CmdXHeader 对象链接到 CommandHeader.payload?
我的解决方案
谢谢大家的回复。我通过以下方式解决了它:
//Get the buffer for CmdXHeader:
size_t cmdXHeader_len = sizeof(CmdXHeader) + custom_len;
CmdXHeader* cmdXHeader = (CmdXHeader*) malloc(cmdXHeader_len);
//Get a temporary pointer and assign the data to it
UINT8* p;
p[0] = 1;
p[2] = 2;
.......
//Now copy the memory of p to cmdXHeader
memcopy(cmdHeader->payload, p, custom_len);
// allocate the buffer for CommandHeader
CommandHeader* commandHeader = (CommandHeader*) malloc (sizeof (CommandHeader) + cmdXHeader_len);
// populate the fields in commandHeader
commandHeader->len = custom_len;
memcpy(commandHeader->payload, cmdXHeader, cmdXHeader_len);
现在 commandHeader 对象具有所需的内存,我们可以用任何我们想要的方式进行类型转换......