Reputation: 353
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 ?
Upvotes: 1
Views: 8633
Reputation: 7044
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.
Upvotes: 2
Reputation: 17329
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.
Upvotes: 0