////////////////////////////////////////////////////////////////// //Dynamically Allocated Matrix struct // //Demo program which showcases a clean way to work with matrices. // //Matthew Miller //July 2007 ///////////////////////////////////////////////////////////////// #include #include ///////////////////////////////////////////////////////////// //Matrix struct // //Used to store a matrix and it's dimensions. //Allows for clean syntax when using matrices. // //To declare a new matrix: Matrix A; ///////////////////////////////////////////////////////////// typedef struct { double ** M; int m; int n; }Matrix; ////////////////////////////////////////////////////////// //Allocate the data portion of a Matrix, given dimensions. // //Note that this does not allocate the struct itself, //only the data protion (double ** M). // //Arguments // //Matric * mat : Pointer to a Matrix. //int m,n : Number of rows/columns. /////////////////////////////////////////////////////////// void MatrixAlloc(Matrix * mat,int m,int n) { int i; //store dimensions in matrix mat->m=m; mat->n=n; //note the arrow operator (->) is used becuase //mat is a pointer to a struct //allocate m row arrays -- this gives us the first subscript mat->M=(double **) malloc(m*sizeof(double*)); //allocate n elements for each row -- this gives us the second subscript for(i=0;iM[i]=(double *) malloc(n*sizeof(double)); } //entries in mat->M can now be referenced as mat->M[i][j] } //Self explanitory void printMatrix(Matrix * mat) { int i,j; for(i=0;im;i++) { for(j=0;jn;j++) { printf("%g ",mat->M[i][j]); } printf("\n"); } } //Just a test function void foo(Matrix * mat) { int i,j; printf("Foo!\n"); for(i=0;im;i++) { for(j=0;jn;j++) { mat->M[i][j]=(i+j)%(mat->m); } } } int main() { //a 10x5 matrix sounds good int m = 10; int n = 5; //declare this way to get struct allocation for free Matrix mat; //allocate the data portion of the matix, note the reference operator (&) MatrixAlloc(&mat,m,n); //foo it foo(&mat); //print it printMatrix(&mat); return 0; }