shuji
shuji

Reputation: 7527

Error when trying to malloc a struct pointer

I am trying to define two bidimensional matrixes in C but the program crashes after creating the second one.

what am I doing wrong?

I am suspicious that it might be the way I return the Matrix from the function but it would be nice if someone can orient me thanks.

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

struct Matriz{
    int m;
    int n;
    int **mat;
};
struct Matriz getMatriz(int index){
    int m, n;
    printf("Input row number for matrix %d: ", index);
    scanf("%d",&m);
    printf("Input column number for matrix %d: ", index);
    scanf("%d",&n);
    struct Matriz *matriz = malloc(sizeof(struct Matriz));  //after this the program crashes
    matriz->m=m;
    matriz->n=n;
    matriz->mat=malloc(m*n*sizeof(int));
    //struct Matriz matriz = {m, n, malloc(m*n*sizeof(int))};
    for(int i=0; i<m; i++)
        for(int j=0; j<n; j++){
            printf("Input row %d, column %d: ", i+1, j+1);
            scanf("%d", &matriz->mat[i][j]);
            printf("input: %d\n", matriz->mat[i][j]);
        }
    fputs("\n", stdout);
    return *matriz;
}
int main(){
    struct Matriz matriz1 = getMatriz(1);
    printf("size1 %d %d\n", matriz1.m, matriz1.n);
    struct Matriz matriz2 = getMatriz(2);  //Cannot create the second matrix
    printf("size2 %d %d\n", matriz2.m, matriz2.n);
    for(int i=0; i<matriz1.m; i++)
        for(int j=0; j<matriz1.n; j++)
            printf("%d", matriz1.mat[i][j]);
        fputs("\n\n", stdout);
    }
    return 0;
}

Upvotes: 0

Views: 119

Answers (2)

Barmar
Barmar

Reputation: 781058

int **mat is the declaration for an array of pointers to int.

malloc(m * n * sizeof(int)) doesn't allocate an array of pointers, it allocates a 1-dimensional array of ints.

The correct way to allocate the matrix is:

matriz->mat = malloc(m * sizeof(int*));
for (int i = 0; i < m; i++) {
    matriz->mat[i] = malloc(n * sizeof(int));
}

Upvotes: 1

recep
recep

Reputation: 124

struct Matriz *matriz = (struct Matriz*)malloc(sizeof(struct Matriz));

You should use type casting for the return of malloc() if you are using a c++ compiler.

Upvotes: 0

Related Questions