我想将数组的内容放在矩阵中。如果矩阵是静态的,一切正常,但是当我尝试动态分配时,读取就不行了。
int main()
{
int a[]={2, 1, 2, 4, 9, 2, 1, 7, 3, 5, 8, 3};
int c[3][4];
int **b;
b = (int**) malloc (3*sizeof(int*));
for (int i=0; i < 3; i++)
b[i] = (int*) calloc (4, sizeof(int)); //o linie
int k=0, m=0;
for (int i=0; i<12; i++)
{
b[k][m]=a[i];
c[k][m]=a[i];
m++;
if((i!=0) && (!(i % 4))) {k++; m=1;}
}
for (int i=0; i<3; i++){
cout << endl;
for (int j=0; j<4; j++)
cout << b[i][j] << " ";
}
cout << endl;
for (int i=0; i<3; i++){
cout << endl;
for (int j=0; j<4; j++)
cout << c[i][j] << " ";
}
return 0;
}
The output:
2 1 2 4
0 1 2 7 //I have 0, why don't I have 9?
0 5 8 3 //I have 0, why don't I have 3?
2 1 2 4
9 1 2 7 //here is correct
3 5 8 3 //here is correct
请告诉我我错了。
答案 0 :(得分:1)
您应将if更改为
if (i % 4 == 3)