使用动态分配的C语言中的矩阵乘法(程序崩溃)

使用动态分配的C语言中的矩阵乘法(程序崩溃),c,pointers,matrix,dynamic-allocation,C,Pointers,Matrix,Dynamic Allocation,正如标题中所述,我有一个程序可以将从文件中读取的矩阵相乘,但当我运行它时,它就会崩溃。我需要有两个函数来执行乘法,一个函数在使用没有返回值的指针时打印结果。感谢您的帮助 #include<stdio.h> #include<stdlib.h> void mat_mult(int ** arr1, int rows1, int cols1, int ** arr2, int rows2, int rcols2, int ** arr3); void mat_ou

正如标题中所述,我有一个程序可以将从文件中读取的矩阵相乘,但当我运行它时,它就会崩溃。我需要有两个函数来执行乘法,一个函数在使用没有返回值的指针时打印结果。感谢您的帮助

#include<stdio.h>
#include<stdlib.h>

void mat_mult(int ** arr1, int rows1, int cols1, int ** arr2, 
    int rows2, int rcols2, int ** arr3);
void mat_out(int ** arr, int rows, int cols);

int main(void){
int **mat1, **mat2, **res, rows1, cols1, rows2, cols2, i, j;
    FILE* f;
    f = fopen("Matrices.txt", "r");
    fscanf(f, "%d", &rows1);
    fscanf(f, "%d", &cols1);
    mat1 = (int**) malloc(rows1*sizeof(int*));
    for(i = 0;i < rows1;i++){
        mat1[i] = (int*)malloc(cols1*sizeof(int));
    }
    for(i = 0;i < rows1;i++){
        for(j = 0;j < cols1;j++){
            fscanf(f, "%d", &mat1[i][j]);
        }
    }
    fscanf(f, "%d", &rows2);
    fscanf(f, "%d", &cols2);
    mat2 = (int**) malloc(rows2*sizeof(int*));
    for(i = 0;i < rows2;i++){
        mat2[i] = (int*)malloc(cols2*sizeof(int));
    }
    for(i = 0;i < rows2;i++){
        for(j = 0;j < cols2;j++){
            fscanf(f, "%d", &mat2[i][j]);
        }
    }
    res = (int**)calloc(rows1,sizeof(int*));
    for(i = 0;i < rows1;i++){
        res[i] = (int*)calloc(cols2,sizeof(int));
    }
    /*mat_mult(mat1, rows1, cols1, mat2, rows2, cols2, res);
    mat_out(res, rows1, cols2);*/

}

void mat_mult(int ** mat1, int rows1, int cols1, int ** mat2, 
    int rows2, int cols2, int ** res){
    int i, j, k;
    for(i = 0;i < rows1;i++){
        for(j = 0;j < cols2;j++){
            res[i][j] = 0;
            for(k = 0;k < cols1;k++){
                res[i][j] += mat1[i][k] * mat2[k][j];
            }
        }
    }
}
void mat_out(int ** res, int rows, int cols){
int i, j;
    for(i = 0;i < rows;i++){
        for(j = 0;j < cols;j++){
            printf("%d ",res[i][j]);
        }
    printf("\n");
    }
}
#包括
#包括
无效材料(整数**arr1,整数行1,整数列1,整数**arr2,
int rows2、int rcols2、int**arr3);
作废材料(整数**arr、整数行、整数列);
内部主(空){
int**mat1,**mat2,**res,行1,列1,行2,列2,i,j;
文件*f;
f=fopen(“matrix.txt”、“r”);
fscanf(f、%d、&rows1);
fscanf(f、%d、&cols1);
mat1=(int**)malloc(行1*sizeof(int*);
对于(i=0;i
我没有看到任何错误,所以我编译并执行了您的程序,它按预期工作,可能您的问题是您添加到文件
matrix.txt
中的数据

我的文件
matrix.txt
是:

2
2
3
2
1
4
2
2
3
2
1
4
此文件将生成2个矩阵,其单元格等于:

3 2
1 4
乘法结果是:


这很好。

您能确定崩溃发生在哪里吗?当您的程序无法工作时,尤其是当它神秘崩溃时,首先要尝试的事情之一是在调试器中运行它。至少,您应该能够找到崩溃发生的位置。但是,在我看来,您的代码运行正常(在取消对
mat_mult()
mat_out()
调用的注释后)。valgrind报告的唯一问题是无法释放分配的内存,而这本身不会导致崩溃。您确定正确定义了
matrix.txt
吗?如果确实发生了崩溃,那么最合理的原因是输入错误。特别是,如果第一个矩阵的第二个维度(读作)大于第二个矩阵的第一个维度,那么您将获得一个越界数组访问。你真的应该确认它们是一样的。(这里我指的是抽象的数学意义上的“矩阵”)我同意。这是一个很好的理由来结束这个问题,或者至少寻求澄清,而不是回答它。好的,非常感谢。我会看看我的文件以及我是如何处理的。