我试图定义一个动态数组,将数据从静态数组复制到动态数组中,然后再复制回静态数组。但似乎数据没有正确复制。我做错什么了吗?
#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