nix*_*get 0 c++ arrays gcc struct memcpy
我想使用memcpy将struct数组的元素复制到另一个.我相信这很可能导致我的程序由于某种原因而失败.另外我怎样才能释放内存?
struct FaultCodes
{
string troubleFound;
string causeCode;
string actionCode;
string paymentCode;
string suppCode;
u_int16_t multiplier;
};
struct JobFaultInfo
{
static const size_t NUM_CODES = 5;
FaultCodes codes[NUM_CODES];
};
FaultCodes codes[JobFaultInfo::NUM_CODES];
// I have populated codes with the data.
JobFaultInfo info;
memcpy(info.codes, codes, sizeof(FaultCodes)*JobFaultInfo::NUM_CODES);
Run Code Online (Sandbox Code Playgroud)
您只允许在情况下使用memcpy你复制的对象是所谓的POD(普通旧数据结构).但是你的struct包含不是POD的std :: string对象.因此,您的整个结构不是POD.
请改用算法标题中的std :: copy.
A std::string通常包含指向存储字符的位置的指针.通过使用memcpy每个字符串,您将获得两个std::string认为必须释放该内存的实例.砰.
您可以使用std::copy从<algorithm>代替.
但更好的是,使用std::vector而不是原始数组.
干杯和hth.