对于包含char数组的结构,memcpy失败

ech*_*Lee 1 c memcpy

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;
}
Run Code Online (Sandbox Code Playgroud)

与那些实用程序功能,如果我做

            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 "
Run Code Online (Sandbox Code Playgroud)

测试src为0,测试dst为1,数据为“ I”,测试num为d,测试is_seq为1。

那么,为什么数据只有2个字符?无损执行此操作的正确方法是什么?

谢谢!

kir*_*dar 5

memcpy(frame,
       char_buf,
       sizeof(char) * sizeof(frame));
Run Code Online (Sandbox Code Playgroud)

应该

memcpy(frame,
       char_buf,
       sizeof(Frame));
Run Code Online (Sandbox Code Playgroud)

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