1

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 ?

3
  • Why do you think something is wrong? Commented Nov 5, 2013 at 18:32
  • Sorry, i forgot the most important ! Commented Nov 5, 2013 at 18:36
  • ".exe has stop working" Did you get an exception thrown ? If yes, what is it ? Commented Nov 5, 2013 at 18:37

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You declare CreateNewMatrix to return a struct:

struct Matrix CreateNewMatrix(unsigned int n,unsigned int m){

But when you use it you expect a pointer to a struct:

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

This should be a compiler error, though.

1 Comment

I don't why but i changed the return of CreateNewMatrix from a struct to pointer and it's now working fine ! Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.