我試圖定義一個動態數組,將數據從靜態數組複製到動態數組中,並將其複製回靜態數組。但似乎沒有正確複製數據。我做錯什麼了嗎?在動態指針數組和靜態數組之間複製數據
#include <stdio.h>
int main(){
int n = 2;
double a[2][2];
double c[2][2];
a[0][0] = 0.0;
a[0][1] = 0.1;
a[1][0] = 1.0;
a[1][1] = 1.1;
double* b = NULL;
double* p = NULL;
int i,j;
b = (double*) malloc(n*n*sizeof(double));
for(i=0; i<n; i++){
for(j=0; j<n; j++){
p = b+i;
*(p+j) = a[i][j];
}
}
memcpy(c, b, sizeof(*b));
for(i=0; i<n; i++){
for(j=0; j<n; j++){
p = b+i;
fprintf(stderr, "[%d][%d] = %.1f, c[%d][%d] = %.1f \n", i, j, *(p+j), i, j, c[i][j]);
}
}
free(b);
b = NULL;
return 0;
}
結果
[0] [0] = 0.0,C [0] [0] = 0.0
[0] [1] = 1.0,C [0] [1] = 0.0
[1] [0] = 1.0,C [1] [0] = 0.0
[1] [1] = 1.1,C [1] [1] = 0.0
好吧,我發現了錯誤。它應該是(i)memcpy(c,b,n * n * sizeof(* b));和(ii)p = b +(i * n); – twfx