我正在尝试复制一个数组。我知道这是“错误代码”,但我是从大量使用此代码和其他低级内容的教程中获得的。出于某种原因,我遇到了运行时错误,我不知道它来自哪里或为什么。谁能帮忙?谢谢。
#include <iostream>
void copy_array(void *a, void const *b, std::size_t size, int amount)
{
std::size_t bytes = size * amount;
for (int i = 0; i < bytes; ++i)
reinterpret_cast<char *>(a)[i] = static_cast<char const *>(b)[i];
}
int main()
{
int a[10], b[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
copy_array(a, b, sizeof(b), 10);
for (int i = 0; i < 10; ++i)
std::cout << a[i] << ' ';
}
最佳答案
表达式 sizeof(b)
返回数组的大小(以字节为单位),而不是数组中元素的数量。这会导致复制函数覆盖堆栈帧,从而导致运行时错误。请改用 sizeof(b[0])
来获取单个元素的大小。如果您想检索数组中元素的数量,您可以像这样结合使用两者。
copy_array(a, b, sizeof(b[0]), sizeof(b) / sizeof(b[0]));
关于c++ - 从数组复制字节时出现运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16682053/