2016-01-11 36 views
1

我想弄清楚如何獲取一小部分數據並使用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是行不通的。

回答

4

測試是一個浮點型指針,sizeof(tmp)是字節大小。

指針算術會導致您錯誤的偏移量。

嘗試:

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

它是一個不是指針的數組。 – Lundin

0

只寫可讀的代碼,所有的問題通常會消失:

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以允許更好的優化)