所以正如標題中所述,我有一個程序可以乘以從文件中讀取的矩陣,但是當我運行它時,它只會崩潰。我需要兩個函數來執行乘法運算,一個使用不帶返回值的指針來打印結果。任何幫助表示讚賞。使用動態分配在C中的矩陣乘法(程序崩潰)
#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");
}
}
你能識別發生碰撞的位置嗎? – ysap
當你的程序無法正常工作時,尤其是當它神祕崩潰時,首先要嘗試的一件事是在調試器中運行它。至少,你應該能夠找到崩潰發生的地方。 –
然而,你的代碼對我來說看起來不錯,而且運行得很好(在對'mat_mult()'和'mat_out()')的調用取消註釋之後)。 valgrind報告的唯一問題是未能釋放分配的內存,而這本身不會導致崩潰。 –