c++ - Runtime error when copying bytes from array -
i'm trying make copy of array. know "bad code" i'm getting tutorial makes heavy use of , other low-level things. reason i'm getting runtime error , can't tell it's coming or why. can help? thanks.
#include <iostream> void copy_array(void *a, void const *b, std::size_t size, int amount) { std::size_t bytes = size * amount; (int = 0; < 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); (int = 0; < 10; ++i) std::cout << a[i] << ' '; }
the expression sizeof(b) returns size of array in bytes not number of elements in array. causes copy function overwrite stack frame resulting in runtime error. use sizeof(b[0]) instead size of individual element. if want retrieve number of elements in array can use combination of 2 so.
copy_array(a, b, sizeof(b[0]), sizeof(b) / sizeof(b[0]));
Comments
Post a Comment