使用 c 中的 memcpy 将多个结构复制到缓冲区中

标签 c

  1. 我有几个结构(u8 字段)要转换成缓冲区,这是最好的方法吗?

    struct struct_a a;
    struct struct_b b;
    u8 buffer[64];
    u8 *next_pos;
    
    os_memcpy(buffer, &a, sizeof(struct_a));
    
    next_pos = buffer + sizeof(struct_a)/sizeof(u8);
    
    os_memcpy(next_pos, &b, sizeof(struct_b));
    
  2. 这是计算缓冲区总长度的最佳方法吗?

    buffer_len = (sizeof(struct_a) + sizeof(struct_b) + ... )/sizeof(u8);
    

谢谢

最佳答案

我假设 u8 表示无符号 8 位。因此,sizeof(u8) 等于 1。所以您可以简单地写:

os_memcpy(&buffer[sizeof(struct_a)], &b, sizeof(struct_b));

对于你的第二个问题,除了除以 1 没有用外,这是计算缓冲区 len 的一种非常好的方法。

我不是 buffer + sizeof(struct_a) 的忠实粉丝,但它也很好。

编辑:此外,在做那​​种事情时,如果缓冲区元素的大小不是 1,我将缓冲区转换成与 u8 等效的东西.这样,我就不必除以缓冲区元素的大小。

关于使用 c 中的 memcpy 将多个结构复制到缓冲区中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19230755/

相关文章:

c++ - C/C++ 中奇怪的数组到指针的转换

c - 在 polarssl c 中签署和验证 rsa 签名

在C中将char数组转换为值并放入int数组

C++ 结构声明 collect2 : ld returned 1 exit status

c - C中二叉树遍历没有输出

c - 如何通过 popen 使用内置 shell 命令

c - 在没有最大缓冲区长度的情况下从 C 中的标准输入读取

为交叉编译器构建 newlib 时出现 'gettimeofday' 的类型冲突

c - 在 linux 中用 c 代替 getch 和 clrscr()

c++ - 使用 C API 的有序 lua 表循环