【发布时间】: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 没有按预期工作。
【问题讨论】: