【问题标题】:structure with variable length C具有可变长度的结构 C
【发布时间】:2015-08-09 11:20:57
【问题描述】:

我在将数据字节放入我的结构时遇到了问题。我正在用 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)

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

【问题讨论】:

  • unsigned char btyte1[1] 只是unsigned char byte1 没有意义,在unsigned char length[2] 的情况下,它将是unsigned short length;。还有Do not cast the return value of malloc(),但一定要检查它不是NULL。请解释一下NO BIG EFFORT!,你的想法是什么,你有没有尝试过任何东西?
  • 我的第一个想法是以这种方式将我的数组转换为我的结构:Packet = (struct Packet*)buffer;这是一个非常短暂的可能性,但我认为它只有在结构中的条目具有相同的数据类型时才有效,对吧?
  • 不知道是不是坏主意,得看代码。
  • 为什么 char byte1[1] 没有意义?如何在结构中保存数组中的 char 值,其定义如下: struct Pointer{ char byte1; char byte2;} *指针;这不起作用:Pointer->byte = array[0];
  • 为什么不起作用?确实如此,除非您的代码有其他问题。我认为您没有发布正确的问题,这意味着您不知道您的程序出了什么问题,这意味着您需要自己尝试弄清楚以及何时你遇到了一个特定的问题,那么你可以去 Stack Overflow 提问,同时我投票结束这个问题。

标签: c struct


【解决方案1】:

首先修复结构体定义:

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

【讨论】:

  • 我不明白这两行:unsigned short length = header[3] * 0x100 + header[4]; // 假设网络字节顺序 Packet *packet = malloc( sizeof *packet + length );我想我必须设置我的数据数组的长度。我的数据数组的长度位于 dataLength 中。如何设置长度?
  • @florian2840 我正在使用flexible array member 的技术,你调用malloc 一次;该块将包含数据,byte1byte2byte3。我的建议是,这比您必须 malloc 一个 Packet 然后还要 malloc 更多数据空间的设置更简单。
  • header[3] * 0x100 + header[4] 将存储在lengthData 中的两个字节转换为整数值。例如这些字节是0x02 0x30,那么长度将为0x230(或560十进制)。您没有说这两个字节中的哪一个是 most significant byte 所以我假设第一个是 ;因为这是通过网络发送整数的最常见方式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-14
  • 2013-11-26
  • 1970-01-01
  • 2011-11-30
  • 1970-01-01
  • 1970-01-01
  • 2011-10-03
相关资源
最近更新 更多