如果我运行程序,它可以让我输入 3 个整数 n、m、p 和矩阵元素。n 是行,m 和 p 是列。但是,它在我输入最终元素后不久就出现了分段错误,就像这样;
4 3 2 输入元素矩阵 1[0][0]: 3 输入元素矩阵 1[0][1]: 9 输入元素矩阵 1[0][2]: 3 输入元素矩阵 1[1][0]: 2 输入元素矩阵 1[1][1]: 7 输入元素矩阵 1[1][2]: 9 输入元素矩阵 1[2][0]: 0 输入元素矩阵 1[2][1]: 5 输入元素矩阵 1[2][2]: 8 输入元素矩阵 1[3][0]: 5 输入元素矩阵 1[3][1]: 4 输入元素矩阵 1[3][2]: 3 输入元素矩阵 2[0][0]: 8 输入元素矩阵 2[0][1]: 3 输入元素矩阵 2[1][0]: 9 输入元素矩阵 2[1][1]: 7 输入元素矩阵 2[2][0]: 8 输入元素矩阵 2[2][1]: 5 分段故障
matrix1 = (int**) malloc(row1 * sizeof(int*));
//read elements of 1st matrix
for (i = 0; i < row1; i++) {
matrix1[i] = (int*) malloc(col1 * sizeof (int));
for (j = 0; j < col1; j++) {
printf("\nEnter element matrix 1[%d][%d]: ", i, j);
scanf("%d", &matrix1[i][j]);
}
}
matrix2 = (int**) malloc(row2 * sizeof (int*));
//read elements of 2nd matrix
for (i = 0; i < row2; i++) {
matrix2[i] = (int*) malloc(col2 * sizeof (int));
for (j = 0; j < col2; j++) {
printf("\nEnter element matrix 2[%d][%d]: ", i, j);
scanf("%d", &matrix2[i][j]);
}
}
//memory allocation of no. of cols in matrix
mtxProduct = (int**) malloc(row1 * sizeof (int*));
//memory allocation of no. of cols in matrix
for (i = 0; i < col2; i++) {
mtxProduct[i] = (int*) malloc(col2 * sizeof (int));
}
//multiplication
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) {
mtxProduct[i][j] = 0;
for (e = 0; e < row2; e++) {
mtxProduct[i][j] +=(matrix1[i][e] * matrix2[e][j]);
}
}
}
//print matrix product
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) {
printf("%d ", mtxProduct[i][j]);
}
printf("\n");
}
return 0;
}