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