Search code examples
cstructdynamic-memory-allocation

Return Struct from Function in C


I'm very new to langage C and I need to make a lot of matrix calculation and I decided to use a matrix struct.

Matrix.h

struct Matrix
{
    unsigned int nbreColumns;
    unsigned int nbreRows;
    double** matrix;
};

struct Matrix CreateNewMatrix(unsigned int n,unsigned int m);
double GetMatrixValue(struct Matrix* m,unsigned int ligne,unsigned int colonne);

Matrix.c

#include "matrix.h"

struct Matrix CreateNewMatrix(unsigned int n,unsigned int m){
    struct Matrix mat;
    mat.nbreColumns = n;
    mat.nbreRows = m;
    mat.matrix = (double**)malloc(n * sizeof(double*));

    unsigned int i;
    for(i = 0; i < n; i++)
    {
        mat.matrix[i] = (double*)calloc(m,sizeof(double));
    }

    return mat;
}

double GetMatrixValue(struct Matrix* m,unsigned int ligne,unsigned int colonne){
    return m->matrix[ligne][colonne];
}

Then I compile, no errors ...

I made a few tests :

Main.c

struct Matrix* m1 = CreateNewMatrix(2,2);

printf("Valeur : %f",GetMatrixValue(m1,1,1));


Edit : When I run my code, I had ".exe has stop working" ..


What did i do wrong ?


Solution

  • CreateNewMatrix returns a Matrix not a Matrix*

    struct Matrix* m1 = CreateNewMatrix(2,2);
    printf("Valeur : %f",GetMatrixValue(m1,1,1));
    

    should be

    struct Matrix m1 = CreateNewMatrix(2,2);
    printf("Valeur : %f",GetMatrixValue(&m1,1,1));
    

    You should compile with all warnings on and not run the program until all the warnings go away.