我試圖做一個數組的副本。我知道這是「糟糕的代碼」,但我從一個教程中獲得它,它大量使用了這個和其他低級別的東西。出於某種原因,我得到一個運行時錯誤,我不知道它來自哪裏或爲什麼。誰能幫忙?謝謝。當從數組中複製字節時出現運行時錯誤
#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(int)'和'sizeof(int *)'比較。現在你學到了一些東西。即**數組不是*指針!**不管*誰*告訴過你。 – dmckee
'sizeof(b)''已經以字節爲單位返回大小......你不需要將它乘以10並重新解釋投射?!?找到一個新的教程。 –