C++ 动态分配矩阵中的读取不正确
我想把数组的内容放在矩阵中。如果矩阵是静态的,则一切正常,但当我尝试动态分配时,读取不正常C++ 动态分配矩阵中的读取不正确,c++,matrix,C++,Matrix,我想把数组的内容放在矩阵中。如果矩阵是静态的,则一切正常,但当我尝试动态分配时,读取不正常 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 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
intmain()
{
inta[]={2,1,2,4,9,2,1,7,3,5,8,3};
INTC[3][4];
国际**b;
b=(int**)malloc(3*sizeof(int*);
对于(int i=0;i<3;i++)
b[i]=(int*)calloc(4,sizeof(int));//o linie
int k=0,m=0;
对于(int i=0;i您应该将if更改为
if (i % 4 == 3)