segmentation fault on a function using a struct

Viewed 32

I was trying to solve a problem using matrices/debugging it,the code is to solve the following problem: "3. Given a real matrix A mxn, verify if exists r repeated elements in A". When compiling my code, the program gives Program received signal SIGSEGV in function fill. What is the cause of segmentation fault?

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
/*
 * 3. Given a real matrix Amxn, verify if exists repeated elements in A
*/
struct Matrix{
    int **M;
    unsigned int m;
    unsigned int n;
    int e;
};
typedef struct Matrix Mtx;

int find(Mtx Matrix)
{
    unsigned int i,j;
    int cont = 0;
    for(i = 0;i<Matrix.m;i++){
        for(j = 0;j<Matrix.n;j++){
            if(Matrix.M[i][j] == Matrix.e){
                cont++; 
            }
        }
    }
    return cont;
}
void alloc2d(int **M,unsigned int m,unsigned int n)
{
    unsigned i;
    M = (int **) malloc(sizeof(int *) * m);
    if(M == NULL){
        fprintf(stderr,"Could not allocate Matrix\n");
        exit(1);
    }
    for(i = 0;i<m;i++){
        M[i] = (int *) malloc(sizeof(int) * n);
        if(M[i] == NULL){
            fprintf(stderr,"Could not allocate Matrix\n");
            exit(1);
        }
    }

}
void free2d(Mtx matrix)
{
    unsigned int i;
    for(i = 0;i<matrix.m;i++){
        free(matrix.M[i]);
    }
    free(matrix.M);
}
void fill(Mtx matrix){
    unsigned int i,j;
    for(i = 0;i<matrix.m;i++){
        for(j = 0;j<matrix.n;j++){
            matrix.M[i][j] = 1;
        }
    }
}
void print_matrix(Mtx matrix)
{
    unsigned int i,j;
    for(i = 0;i<matrix.m;i++){
        for(j = 0;j<matrix.n;j++){
            printf("%d ",matrix.M[i][j]);
        }
        printf("\n");
    }
}
int main(void)
{
    Mtx Mtrix;
    Mtrix.m = 2;
    Mtrix.n = 3;
    Mtrix.M = 0x0;
    alloc2d(Mtrix.M,Mtrix.m,Mtrix.n);
    unsigned int j,k;
        fill(Mtrix);
    print_matrix(Mtrix);
    for(j = 0;j<Mtrix.m;j++){
        for(k=0;k<Mtrix.n;k++){
            Mtrix.e = Mtrix.M[j][k];
            int c = find(Mtrix);
            if(c != 0){
                printf("%d found %d times\n",Mtrix.e,Mtrix.M[j][k]);
            }
        }
    }
    
}

what should I do? I tryed intializing the Matrix with 0x0 before calling fill.

0 Answers
Related