复制较小的阵列到阵列较大 [英] copy smaller array into larger array

查看:173
本文介绍了复制较小的阵列到阵列较大的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two arrays of chars, allocated as follows:

 unsigned char *arr1 = (unsigned char *)malloc((1024*1024) * sizeof(char));
 unsigned char *arr2 = (unsigned char *)malloc((768*768) * sizeof(char));

我想ARR2到ARR1复制,但preserve行/列结构。这意味着,只在第一个768个字节每个第一768行的将在ARR1被改变。

I would like to copy arr2 into arr1, but preserve the row/column structure. This means that only the first 768 bytes of each of the first 768 rows will be changed in arr1.

我写了一个for循环,但它不够快满足我的需求。

I wrote a for loop for this, but it's not fast enough for my needs.

for (int x = 0; x < 768; x++) //copy each row
{
    memcpy(arr1+(1024*x),arr2+(768*x), nc);
}

有没有更好的解决办法?

Is there a better solution?

推荐答案

也许摆脱了乘法

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


修改 D'哦!使用指针!

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

这篇关于复制较小的阵列到阵列较大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆