若我运行程序,它可以让我输入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;
}
for (i = 0; i < col2; i++) {
mtxProduct[i] = (int*) malloc(col2 * sizeof (int));
}
在for循环的头中应该是row1而不是col2。分段错误意味着您试图访问内存中不应该尝试访问的位置。因此,您应该查找访问未初始化指针或越界数组元素的代码行。