Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!ucbvax!decwrl!sun!pitstop!sundc!seismo!uunet!mcvax!ukc!etive!lfcs!sam From: sam@lfcs.ed.ac.uk (S. Manoharan) Newsgroups: comp.lang.c Subject: Two Dimensional Arrays. Message-ID: <1474@etive.ed.ac.uk> Date: 24 Feb 89 20:42:18 GMT Sender: news@etive.ed.ac.uk Reply-To: sam@lfcs.ed.ac.uk (S. Manoharan) Organization: Laboratory for the Foundations of Computer Science, Edinburgh U Lines: 56 Passing a 2-D array around different functions does not seem nice, for one needs to declare the dimensions of the array in each and every function. The only way to overcome this problem is to use pointers instead of arrays. As an added advantage, we can allocate the space at runtime. In order to represent a 2-D array, I came up with the following: typedef union { double dv; long lv; } mat_decl; typedef enum { _double, _long } mat_type; mat_decl *MatRead(FILE *fp, int n, int m, mat_type type); /* Read matrix of type mat_type, size nXm from FILE ; return pointer to the first element */ void MatPrint(FILE *fp, mat_decl *A,int n, int m, mat_type type); /* Print matrix A of type mat_type, size nXm to FILE */ We can access the (i,j) the element of the array M as _M(i,j): #define _M(i,j) ((M + m*i + j)->lv) /* m: no. of columns */ The use of union is simply to make the matrix functions general. For example: mat_decl *MatRead(fp,n,m,type) FILE *fp; int n,m; mat_type type; { int j; mat_decl *A, *head; char *calloc(); if ( ( A = (mat_decl *)calloc((unsigned) (n*m),sizeof(mat_decl)) ) == (mat_decl *)0 ) return ( (mat_decl *) 0); head = A; for ( j = 0; j < n*m; ++j, ++A ) switch ( type ) { case _double: fscanf(fp,"%lf",&(A->dv)); break; case _long: fscanf(fp,"%ld",&(A->lv)); break; } return head; } /* EnMatRead */ Now, coming to the query, is there a better/elegant way of coding an array sothat one can use his matrix functions ( say, transpose, inverse, read, write, ... ) for all array types ( double, long, .. ) and sizes? --- sam%uk.ac.edinburgh.lfcs%uk.ac.ucl.cs.nss@net.cs.relay