我有两个字符数组,分配如下:
unsigned char *arr1 = (unsigned char *)malloc((1024*1024) * sizeof(char));
unsigned char *arr2 = (unsigned char *)malloc((768*768) * sizeof(char));
我想将arr2复制到arr1,但保留行/列结构。这意味着将在arr1中仅更改前768行中每行的前768字节。
我为此编写了一个for循环,但是它不够快,无法满足我的需求。
for (int x = 0; x < 768; x++) //copy each row
{
memcpy(arr1+(1024*x),arr2+(768*x), nc);
}
有更好的解决方案吗?
最佳答案
也许摆脱乘法
size_t bigindex = 0, smallindex = 0;
for (int x = 0; x < 768; x++) //copy each row
{
memcpy(arr1 + bigindex, arr2 + smallindex, nc);
bigindex += 1024;
smallindex += 768;
}
编辑!使用指针!
unsigned char *a1 = arr1;
unsigned char *a2 = arr2;
for (int x = 0; x < 768; x++) //copy each row
{
memcpy(a1, a2, nc);
a1 += 1024;
a2 += 768;
}
关于c++ - 将较小的数组复制到较大的数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3746811/