2017-04-11 4 views
-1

제목에서 언급했듯이 파일에서 읽은 행렬에 곱셈을 적용하는 프로그램이 있지만 실행했을 때 충돌이 발생합니다. 곱셈을 수행하는 두 가지 함수와 반환 값이없는 포인터를 사용하여 결과를 출력하는 함수가 필요합니다. 어떤 도움을 주셔서 감사합니다.동적 할당 (프로그램 충돌)을 사용하는 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"); 
    } 
} 
+0

어디에서 충돌이 발생했는지 확인할 수 있습니까? – ysap

+0

프로그램이 작동하지 않을 때, 특히 신비하게 충돌 할 때 가장 먼저 시도 할 것은 디버거에서 실행하는 것입니다. 최소한 충돌이 발생한 곳을 찾을 수 있어야합니다. –

+1

그러나 코드는 괜찮아 보이고 ('mat_mult()'와'mat_out()')의 호출을 주석 해제 한 후 잘 실행됩니다. valgrind가보고하는 유일한 문제는 할당 된 메모리를 해제하지 않아도되고, 그 자체로 충돌을 일으키지 않습니다. –

답변

0

나는 오류를 보지 않았다, 그래서 나는 컴파일하고 프로그램을 실행하고 예상대로, 어쩌면 문제는 당신이 당신의 파일 Matrices.txt에 추가 된 데이터이었습니다했다.

내 파일 Matrices.txt은 :

2 
2 
3 
2 
1 
4 
2 
2 
3 
2 
1 
4 

이 파일은 동일한 셀 2 행렬을 생성 할 것이다 :

3 2 
1 4 

승산 결과 :

enter image description here

어느 완벽하게 괜찮습니다.

+0

동의합니다. 그리고이 질문에 대한 대답 대신에 질문을 마감하거나 명확한 설명을 구할 수있는 좋은 이유입니다. –

+0

좋습니다. 내 파일을보고 처리하는 방법을 살펴 보겠습니다. –