【问题标题】:memcpy to concat smaller arrays into bigger onesmemcpy 将较小的数组连接成较大的数组
【发布时间】:2016-01-11 07:17:51
【问题描述】:

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

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

所以我设置了一个 dest 缓冲区和一个 src 缓冲区以及要复制的数据量。

我一直在尝试,但没有得到我期望的结果。我只想将 4 值浮点数组的 8 个副本打包到一个 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 没有按预期工作。

【问题讨论】:

    标签: c arrays buffer memcpy


    【解决方案1】:

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

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

    尝试:

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

    【讨论】:

      【解决方案2】:

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

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

      (如果你想更高级/更高级,请将参数声明为float* restrict destconst float* restrict src 以便更好地优化)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-09
        • 2020-05-18
        • 2020-02-20
        • 1970-01-01
        相关资源
        最近更新 更多