我想弄清楚如何获取一小部分数据并使用memcopy将它组合成一个更大的数组。这是在c中,而不是C++。memcpy将较小的数组连接成较大的数组
memcpy(void* dest, void* src, size_t n);
所以我设置了dest缓冲区的src缓冲区和要复制的数据量。
我一直在尝试,但我没有得到我期望的结果。我只想获取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是行不通的。
它是一个不是指针的数组。 – Lundin