2016-09-06 32 views
-3

在我的以下代碼中,我將buffer設爲使用malloc(r * c * sizeof(double*));創建的二維數組。我想用memcpybuffer的前12個元素(即前4行)複製到第二個temp使用memcpy複製內存塊時的問題

double *buffer = malloc(10 * 3 * sizeof(double*)); 
double *temp = malloc(4 * 3 * sizeof(double*)); 

    for (int i = 0; i < 4; ++i) { 
     memcpy(*(temp+ i*3), *(buffer + i*3), 3 * sizeof(double)); 
    } 

我得到這個錯誤:

memcpy(*(temp+ i*3), *(buffer + i*3), 3 * sizeof(double)); 
     ^~~~~~~~~~~~~~~~~~~~~~~~~~ 

有人能告訴我爲什麼嗎?

預先感謝您。

+4

當然這不是編譯器的診斷的全部? – EOF

+0

沒有二維數組,而是一維數組。任何你不使用二維數組的原因,但手動做索引數學? – Olaf

+0

什麼是錯誤信息?看[問]並提供[mcve]。 – Olaf

回答

2
double *buffer = malloc(10 * 3 * sizeof(double*)); 

這是不對的,一個指向double想空間對於n double S(不是n個指針,以double

更改爲

double *buffer = malloc(10 * 3 * sizeof(double)); 

同爲temp

I want to copy the first 12 elements of buffer (i.e. the first 4 rows) into the second one temp using memcpy

使用:

memcpy(temp, buffer, sizeof(double) * 12); 

I get this error:

> memcpy(*(temp+ i*3), *(buffer + i*3), 3 * sizeof(double)); 
>  ^~~~~~~~~~~~~~~~~~~~~~~~~~ 

Can someone tell me why?

memcpy想要一個指針(地址),但你解引用指針(由此傳遞一個值一樣3.14而不是地址)

你想一個真正的二維數組?

在這種情況下,你應該使用

double (*buffer)[cols] = malloc(sizeof(*buffer) * rows); /* VLA (since C99) */ 

看看到defining a 2D array with malloc and modifying it

+0

或使用二維數組... – Olaf

+0

非常感謝你 –

+0

@Olaf,你是對的,但在我看來,OP想要一個平面二維數組(由於在malloc中傳遞的維數) –