gpt4 book ai didi

c - 接收两个矩阵的元素后出现分割错误

转载 作者:行者123 更新时间:2023-11-30 14:24:07 25 4
gpt4 key购买 nike

如果我运行程序,它会让我输入 3 个整数 n、m、p 和矩阵元素。 n 是行,m 和 p 是列。但是,在我输入最终元素后不久,它就显示段错误,如下所示;

432Enter element matrix 1[0][0]: 3Enter element matrix 1[0][1]: 9Enter element matrix 1[0][2]: 3Enter element matrix 1[1][0]: 2Enter element matrix 1[1][1]: 7Enter element matrix 1[1][2]: 9Enter element matrix 1[2][0]: 0Enter element matrix 1[2][1]: 5Enter element matrix 1[2][2]: 8Enter element matrix 1[3][0]: 5Enter element matrix 1[3][1]: 4Enter element matrix 1[3][2]: 3Enter element matrix 2[0][0]: 8Enter element matrix 2[0][1]: 3Enter element matrix 2[1][0]: 9Enter element matrix 2[1][1]: 7Enter element matrix 2[2][0]: 8Enter element matrix 2[2][1]: 5Segmentation fault
    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。段错误意味着您尝试访问内存中不应该访问的位置。因此,您应该查找访问未初始化指针或越界数组元素的代码行。

关于c - 接收两个矩阵的元素后出现分割错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12216659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com