1
struct Frame_t
{
    uint16_t src_id;
    uint16_t dst_id;
    unsigned char num;
    uint8_t is_seq;
    char data[48];
};
typedef struct Frame_t Frame;
char *convert_frame_to_char(Frame *frame)
{
    char *char_buffer = (char *)malloc(64);
    memset(char_buffer,
           0,
           64);
    memcpy(char_buffer,
           frame,
           64);
    return char_buffer;
}

Frame *convert_char_to_frame(char *char_buf)
{
    Frame *frame = (Frame *)malloc(sizeof(Frame));
    memset(frame->data,
           0,
           sizeof(char) * sizeof(frame->data));
    memcpy(frame,
           char_buf,
           sizeof(char) * sizeof(frame));
    return frame;
}

如果我这样做的话,可以给出这些效用函数

            Frame *outgoing_frame = (Frame *)malloc(sizeof(Frame));
//   outgoing_cmd->message  contains "I love you"
            strcpy(outgoing_frame->data, outgoing_cmd->message);
            outgoing_frame->src_id = outgoing_cmd->src_id; // 0
            outgoing_frame->dst_id = outgoing_cmd->dst_id; // 1
            outgoing_frame->num = 100;
            outgoing_frame->is_seq = 1;
            //Convert the message to the outgoing_charbuf
            char *outgoing_charbuf = convert_frame_to_char(outgoing_frame);
            // Convert back
            Frame *test = convert_char_to_frame(outgoing_charbuf);
            // print test->data is "I "

test src 为 0,test dst 为 1,data 为“I”,test num 为 d,test is_seq 为 1。

那么,为什么数据只有 2 个字符?无损地做到这一点的正确方法是什么?

谢谢!

4

2 回答 2

5
memcpy(frame,
       char_buf,
       sizeof(char) * sizeof(frame));

应该

memcpy(frame,
       char_buf,
       sizeof(Frame));

size(frame)是指针的大小。因此,您只是size of pointer从数组中复制字节。

于 2019-10-15T06:29:53.340 回答
1

这:

memcpy(frame, char_buf, sizeof(char) * sizeof(frame));

正如评论中指出的那样,没有任何意义。在这里乘以大小是不合逻辑的。

因为frame是一个指针,我认为最好的办法是在sizeof指针指向的东西上使用,因为那是被复制(到)的东西:

memcpy(frame, char_buf, sizeof *frame);

这也温和地将被复制的字节数“锁定”到目标缓冲区的大小,而不重复类型名称,这可能很好。

另请记住,这sizeof不是函数,仅当参数是类型名称时才需要括号,因为它们是参数的一部分(在这种情况下看起来像强制转换)。

于 2019-10-15T08:14:04.387 回答