std::copy :复制只发生在 1 个字节,而不是指定的长度
std::copy : copy is happening only for 1 byte and not for specified length
请参阅下面的代码片段:
#include <iostream>
using namespace std;
int main()
{
uint32_t len, x;
char abc[] = "12345678";
uint8_t *ptr = (uint8_t *)abc;
copy(ptr, ptr + 4, reinterpret_cast<uint32_t*>(&len));
cout << " len: " << len << endl;
}
输出为 49!我希望输出为 1234。我错过了什么吗
您的目标是长度为 1 的"容器"(即单个对象,len
)。
您将四个后续字节值复制到此容器中,这当然会失败 - 特别是,它会导致溢出,因为目标只有单个元素的空间。
代码中的其他错误(并非详尽列表):
- 您混淆了字符代码及其字符串表示形式
- 您正在执行冗余转换
特别是第一点是相关的,因为您实际想要做的是将字符串前四个字符中编码的数字解析为十进制数。但你实际做的是复制它的字符代码。
要解析 C++ 中的数字,请使用 std::stringstream
或自 C++11 起std::stoi
std:copy 无法按预期工作。它将源"按元素"复制到目标。因此,它将第一个 uint8(= char '1' == 十六进制中的 0x49)复制到 'len',然后继续践踏内存中的三个随机 uint32 值。
这是为了看看实际发生了什么。
#include <iostream>
using namespace std;
int main()
{
uint32_t len[4];
char abc[] = "12345678";
copy(abc, &abc[4], &len[0]);
cout << " len: " << len[0] << " " <<len[1] << " " << len[2] << " " << len[3] << endl;
}
首先,std::copy
大致这样做:
template <typename InputItr, typename OutputItr>
void copy(InputItr begin, InputItr end, OutputItr obegin)
{
while (begin != end)
*obegin++ = *begin++;
}
您的输出迭代器是 uint32_t*
,这实际上会导致您覆盖 4 个 32 位字!(缓冲区溢出)。您看到49
因为复制的第一个字符 ( '1'
) 的 ASCII 值为 49。
相关文章:
- 复制初始化:为什么即使关闭了复制省略,也没有调用move或copy构造函数
- 对链表复制构造函数和赋值运算符使用 copy() 方法
- 可以使用 std::copy 将 3D 数组复制到矢量
- 如何使用 std::copy 将一个 constexpr 数组复制到另一个 constexpr 数组
- 为什么我不能在我的复制构造函数中使用 std::copy?
- 在不使用 std::copy 函数的情况下编写这个复杂的复制结构体
- std::copy 将双精度数组复制到浮点数数组
- std::copy :复制只发生在 1 个字节,而不是指定的长度
- 为什么 std::copy 抛出错误向量迭代器 + 偏移量超出范围并且无法复制
- 使用 .Copy 执行复制构造函数的最佳方法
- 使用 std::copy 复制到 std::d eque
- std::copy 和容器的复制构造函数之间是否存在任何性能差异?
- 复制构造函数中的std::copy出错
- 使用std::copy从随机数分布中进行复制
- 在Windows上使用std::copy来复制宽字符串
- 使用std::copy将char数组中的两个字节复制到无符号short中
- 在使用std::copy而不是std::memcpy复制字符时避免libc函数调用
- 使用std::copy复制缓冲区
- 复制std::vector:prefer赋值或std::copy
- 使用std::copy复制单个字符