I tried to define a dynamic array, copy the data from a static array into the dynamic array, and copy back to a static array. But it seems that the data is not copied properly. Did I do something wrong?
#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;
}
result
[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