将较小的数组复制到较大的数组

我有两个字符数组,分配如下:

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; } 

可能最初将其分配为768个单独的数组,而不是复制整个内容,然后使用realloc来扩展它们而不是复制?

不确定它是否真的可以节省任何时间到最后有多次单独调用malloc()而不是move循环。 但如果你不得不多次复制,它可能会。 它还假设您不想进一步修改原始…

你的意思不够快? 你有基准吗?

我想你的nc只是一个代表768的命名常量?

如果你使用编译器提供的内置memcpy,那么没有太多会更快。 您的方法中可能存在的问题:

  • 对齐问题
  • 你的常数nc不是编译时常量
  • 你没有正确的编译器标志