简体   繁体   English

从数组复制字节时出现运行时错误

[英]Runtime error when copying bytes from array

I'm trying to make a copy of an array. 我正在尝试复制数组。 I know this is "bad code" but I'm getting it from a tutorial that makes heavy use of this and other low-level things. 我知道这是“错误的代码”,但是我从大量使用此代码和其他低级内容的教程中得到了它。 For some reason I'm getting a runtime error and I can't tell where it's coming from or why. 由于某种原因,我遇到了运行时错误,我无法知道它来自何处或原因。 Can anyone help? 有人可以帮忙吗? Thanks. 谢谢。

#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] << ' ';
}

The expression sizeof(b) returns the size of the array in bytes not the number of elements in the array. 表达式sizeof(b)返回以字节为单位的数组大小,而不是数组中元素的数目。 This causes the copy function to overwrite the stack frame resulting in a runtime error. 这将导致复制功能覆盖堆栈帧,从而导致运行时错误。 Use sizeof(b[0]) instead to get the size of an individual element. 使用sizeof(b[0])代替获取单个元素的大小。 If you want to retrieve the number of elements in an array you can use a combination of the two like so. 如果要检索数组中的元素数,可以像这样使用两者的组合。

copy_array(a, b, sizeof(b[0]), sizeof(b) / sizeof(b[0]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM