我想将数组的内容放入矩阵中。如果矩阵是静态的,则一切正常,但是当我尝试动态分配时,则无法读取。
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
请告诉我我错了。
您应该将if更改为
if (i % 4 == 3)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句