c - 可变长度结构C

标签 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

通过读取命令,我可以重播数据。

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

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

最佳答案

首先修复结构体定义:

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...

关于c - 可变长度结构C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30481343/

相关文章:

c - 删除文件中的记录(C语言编程)

c++ - windows.h 之间的区别stdafx.h

c - 带有指向结构内部 char 的指针的段错误,ANSI C 代码

c - 如何在后台XCreateWindow?

c - 如何在 C 中正确使用字符串?

c - Luhn算法有时有效有时失败

c - c头文件中的静态结构声明和初始化

使用函数 (ANSI C) 更改结构及其成员包含的地址

linux - 内核调度代码(linux)中的 struct rq 在哪里??/

c - malloc 结构指针抛出段错误(核心已转储)