从偏移位置开始复制存储器

时间:2012-08-16 21:49:17

标签: c++ offset memcpy

如何从给定的偏移量开始复制内存。 例如

int main()
{
   int a1[100], a2[100], i;
   errno_t err;

   // Populate a2 with squares of integers
   for (i = 0; i < 100; i++)
   {
      a2[i] = i*i;
   }

   // Tell memcpy_s to copy 10 ints (40 bytes), giving
   // the size of the a1 array (also 40 bytes).
   err = memcpy_s(a1, sizeof(a1), a2, 10 * sizeof (int) );    
   if (err)
   {
      printf("Error executing memcpy_s.\n");
   }
   else
   {
     for (i = 0; i < 10; i++)
       printf("%d ", a1[i]);
   }
   printf("\n");
}

如何从a1的索引50开始将内存从a2复制到a1。

提前致谢

2 个答案:

答案 0 :(得分:6)

a1添加50。添加时无需乱搞sizeof;编译器知道如何做到这一点。

答案 1 :(得分:5)

将地址传递给您要复制到的索引作为memcpy的目的地:

memcpy(&a1[50], &a2[50], 10 * sizeof a[0]);