0
我試圖運行這段代碼時面向分段錯誤問題:代碼符號/ 乘法 /後分段故障而矩陣乘法,C
#include<stdio.h>
#include<stdlib.h>
int mallocMatrix (int ***matrix, int A, int B) {
int i;
*matrix=(int**)malloc(sizeof(int*)*B);
for(i=0;i<A;i++)
(*matrix)[i]=(int*)malloc(sizeof(int)*A);
};
void fillMatrix (int ***matrix, int A, int B) {
int i, j;
for(i=0;i<B;i++)
{
for(j=0;j<A;j++)
{
printf("Matrix[%d][%d]: ",i+1,j+1);
scanf("%d", &(*matrix)[i][j]);
}
}
};
void displayMatrix (int ***matrix, int A, int B) {
int i, j;
printf ("\n");
for(i=0;i<B;i++)
{
for(j=0;j<A;j++)
{
printf ("%d ", (*matrix)[i][j]);
}
printf ("\n");
}
};
int main(){
int **matrix;
int **matrix_two;
int **matrix_three;
int a, b, c, d;
printf ("[1st matrix] number of columns:");
scanf ("%d", &a);
printf ("[1st matrix] number of rows:");
scanf ("%d", &b);
mallocMatrix (&matrix, a, b);
fillMatrix (&matrix, a, b);
printf ("[2nd matrix] number of columns:");
scanf ("%d", &c);
printf ("[2nd matrix] number of rows:");
scanf ("%d", &d);
if (a==d)
{
mallocMatrix (&matrix_two, c, d);
fillMatrix (&matrix_two, c, d);
}
else
{
printf ("The number of columns of the 1st. matrix must be equal to the number of rows of the 2nd. matrix");
return -1;
}
displayMatrix (&matrix, a, b);
displayMatrix (&matrix_two, c, d);
mallocMatrix (&matrix_three, b, c);
/* multiplication */
int i, j, k;
for(i = 0; i < b; i++)
{
for(j = 0; j < c; j++)
{
for(k = 0; k < b; k++)
{
matrix_three[i][j] = matrix_three[i][j] + matrix[i][k] * matrix_two[k][j];
}
}
}
/* end of multiplication */
displayMatrix (&matrix_three, b, c);
}
問題彈出。例如: - 第一個矩陣是2x2, - 第二個3x2。 我期待結果爲3x2矩陣,但試圖達到第三列時,BUT代碼會給我2x2矩陣和分段錯誤。請點誤差
您使用的崩潰B作爲列數或行數?,我的意思是在mallocMatrix中,我說,嘿! mallocMatrix(矩陣,3,2)是一個3x2矩陣? – DGomez 2012-04-20 15:05:42
b用作行計數 – user1346765 2012-04-20 15:08:16
按照此順序,不能乘以尺寸爲2X2和3X2的兩個矩陣。然而,你可以多用2X2的3X2,得到尺寸爲3X2的矩陣。另外,2X2和2X3矩陣可以相乘,這將得到尺寸爲2X3的結果矩陣。 – tafa 2012-04-20 15:10:54