memcpy 将较小的数组连接成较大的数组

memcpy to concat smaller arrays into bigger ones

我正在尝试弄清楚如何使用 memcopy 获取少量数据并将其组合成一个更大的数组。这是在 c 而不是 c++ 中。

memcpy(void* dest, void* src, size_t n);

所以我设置了目标缓冲区、源缓冲区和要复制的数据量。

我一直在努力,但没有得到预期的结果。我只想取 8 个 4 值浮点数组的副本并将其打包到一个 32 值浮点数组中。

float test[32];
float tmp[4] = {9, 8, 7, 6};
printf("size of tmp:%lu sizeof tmp/ tmp[0]:%lu\n", sizeof(tmp),
       (sizeof(tmp) / sizeof(tmp[0])));
printf("============\n");

执行 printf 来检查大小,4 个浮点数是 16,1 个浮点数的大小是 4,我只是检查完整性。

memcpy(test, tmp + (sizeof(tmp)*0), sizeof(tmp));  //this is the initial offset at 0
memcpy(test + (sizeof(tmp)*1), tmp, sizeof(tmp)); //this should copy to the test buffer plus and offset of 16 bytes
memcpy(test + (sizeof(tmp)*2), tmp, sizeof(tmp)); //etc

for (int i = 0; i < 32; i++) {
    printf("%f ", test[i]);
    if (i > 1 && i % 4 == 0) printf("\n");
}

好像只复制了前 4 个字节,后面的都失败了。

使用偏移等的原因是我想概括这一点,但即使写出这样一个仅复制 16 字节偏移的简单用例也不起作用。

我得到这个打印输出:

size of tmp:16 sizeof tmp/ tmp[0]:4
============
9.000000 8.000000 7.000000 6.000000 0.000000
0.000000 0.000000 0.000000 1602397014491231940111075790290944.000000
0.000000 -6544621971295550046208.000000 0.000000 0.000000
0.000000 1602345021009581954139530027073536.000000 0.000000 9.000000
8.000000 7.000000 6.000000 0.000000
0.000000 -1796536614528950701815653974964961280.000000 0.000000 0.000000
0.000000 0.000000 0.000000 1602345021009581954139530027073536.000000

现在我可以理解随机数意味着内存没有正确初始化,但我不明白为什么 memcpy 没有按预期工作。

test是一个浮点指针,sizeof(tmp)是字节大小。

指针运算会导致您转到错误的偏移量。

尝试:

memcpy(test + ((sizeof(tmp)/sizeof(tmp[0]))*1), tmp, sizeof(tmp))

只需编写可读代码,所有问题通常都会消失:

void copy_floats (float*        dest, 
                  const float*  src, 
                  size_t        items_n,
                  size_t        copies_n)
{
  for(size_t i=0; i<copies_n; i++)
  {
    memcpy(&dest[i * items_n], 
           src, 
           sizeof(*src) * items_n);
  }
}

来电者:

copy_floats(test, tmp, 4, 8);

(如果你想成为predantic/advanced,将参数声明为float* restrict destconst float* restrict src以允许更好的优化)