长度可变的结构C.

时间:2015-05-27 11:37:57

标签: c struct

我有问题要将数据库添加到我的结构中。我在C编程 我收到的字节看起来像这样:

Byte1 | Byte 2 | Byte 3| lengthData (2 Bytes) | data (variable)

我的结构看起来像这样:

struct Packet {
   unsigned char byte1[1];
   unsigned char byte2[1];
   unsigned char byte3[1];
   unsigned char length[2];
   unsigned char * data; 
}*Packet

通过read命令,我有重播数据。

char * replay;
replay = (char*) malloc (MAX_DATA_LENGTH);
memset(replay, 0x00, MAX_DATA_LENGTH);
read(fd, replay, MAX_DATA_LENGTH)

现在我想将数据字节放入结构中。首先,我必须为指针数据分配内存。我的问题是,如何在结构中不费力地获取数据?

1 个答案:

答案 0 :(得分:0)

首先修复结构定义:

typedef struct Packet {
   unsigned char byte1, byte2, byte3;
   unsigned short length;
   unsigned char data[];
} Packet;   // note: no bogus star

以下是便携式阅读的一种方式:

unsigned char header[5];
if ( 5 != read(fd, header, 5) )
    // error handling... 

unsigned short length = header[3] * 0x100 + header[4]; // assuming network byte order
Packet *packet = malloc( sizeof *packet + length );
if ( !packet )
    // error handling....

packet->byte1 = header[0];
packet->byte2 = header[1];
packet->byte3 = header[2];
packet->length = length;
ssize_t num_read = read(fd, packet->data, length);

if ( num_read != length )
    // error handling...