gpt4 book ai didi

c - memcpy 对包含 char 数组的结构失败

转载 作者:太空宇宙 更新时间:2023-11-04 00:43:07 25 4
gpt4 key购买 nike

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 个字符?无损执行此操作的正确方法是什么?

谢谢!

最佳答案

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

应该是

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

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

关于c - memcpy 对包含 char 数组的结构失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58388290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com