You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中将两个结构体数据复制合并到同一目标内存?

解决方案

你没法通过一次memcpy调用完成两个不同源数据的合并,因为memcpy的第二个参数只能接收单个内存块的起始指针。正确的做法是分两次调用memcpy,依次将两个结构体的数据复制到目标内存的对应位置:

struct M{
   int a;
   int b;
}m;

struct N{
   int c;
   int d;
}n;

std::vector<std::uint8_t> destination(sizeof(M)+sizeof(N));
// 先复制结构体m的数据到目标起始位置
memcpy(destination.data(), &m, sizeof(M));
// 再复制结构体n的数据到m之后的内存位置
memcpy(destination.data() + sizeof(M), &n, sizeof(N));

额外说明

  • 注意结构体的内存对齐问题:如果你的结构体使用了特殊的对齐规则(比如#pragma pack),sizeof(M)+sizeof(N)可能不等于合并后实际占用的内存大小,这种情况下需要手动确认总长度。
  • 如果你偏好更符合C++风格的实现,也可以用std::copy替代memcpy,对于这类简单的POD结构体,两者效率相当:
    std::copy(reinterpret_cast<const uint8_t*>(&m), 
              reinterpret_cast<const uint8_t*>(&m) + sizeof(M), 
              destination.begin());
    std::copy(reinterpret_cast<const uint8_t*>(&n), 
              reinterpret_cast<const uint8_t*>(&n) + sizeof(N), 
              destination.begin() + sizeof(M));
    

内容的提问来源于stack exchange,提问作者jkafernando

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 22:15:28