Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Path: utzoo!mnetor!seismo!rochester!pt!ius2.cs.cmu.edu!edw From: edw@ius2.cs.cmu.edu (Eddie Wyatt) Newsgroups: comp.lang.c Subject: Re: Two dimensional arrays in C Message-ID: <1213@ius2.cs.cmu.edu> Date: Tue, 23-Jun-87 10:17:08 EDT Article-I.D.: ius2.1213 Posted: Tue Jun 23 10:17:08 1987 Date-Received: Sun, 5-Jul-87 18:38:25 EDT References: <733@cod.UUCP> Organization: Carnegie-Mellon University, CS/RI Lines: 113 Keywords: ? In article <733@cod.UUCP>, murphys@cod.UUCP (Steven P. Murphy) writes: > > > The following example is what I would like to be able to do. Is it possible ? > > I tried something like this twice but it didn't work either time, though > it be from my inexperience with C. > > > > #define ROWS1 500 > #define COLUMNS1 30 > > #define ROWS2 400 > #define COLUMNS2 20 > > main() > { > static double data1[ROWS][COLUMNS]; > static double data2[ROWS][COLUMNS]; > > int n, m; > > n1 = 300; > m1 = 15; > n2 = 200; > m2 = 18; > . > . > . > matrix_stuff(n1, m1, data1, ROWS1, COLUMNS1); > . > . > . > matrix_stuff(n2, m2, data2, ROWS2, COLUMNS2); > . > . > . > } /* end of main */ > > > > matrix_stuff(a, b, array, x, y); > > int a, b, x, y; > double array[x][y]; > > { > int i, j; > . > . > . > for(i = 0;i <= a;i++) /* step through the rows */ > for(j = 0;j <= b;j++) /* step through the columns */ > { > operate on the part of the > matrix "array" that was used in main > } > . > . > . > } /* end of matrix_stuff */ In the direct way, unfortunately no. I can see no reason why C doesn't support a construct like that, Fortrash does. And it wouldn't make the code generated much less efficient - the index function could have the dimensions plugged in when the matrix function is called. Note, I said not much less efficient - there may be some optimizations that the compiler may realize about the array indexes that it can't with "dynamic" bounds. One posible solution is to treat the matrix as an array of doubles and write you own indexing function. Example : matrix_stuff(a,b,array,x,y) int a,b,x,y; double array[]; { register int i,j; ..... for (i = 0; i <= a; i++) for (j = 0; j <= b; j++) { submatrix[i][j] = array[i*y+j]; /* indexing function ^ */ ...... } } In general, the indexing function in C for type a[N1][N2]...[Nn]; a[I1][I2]...[In] is *( sizeof(type)*(In + Nn*(I{n-1} +N{n-1}*(I{n-2} + N{n-2}.... N3*(I2 + N2*I1))))...) By declaring the array "array" to be an array of doubles you in a sence fill in the sizeof value and supply the pointer operation. This indexing function is use because arrays are in is that column or row major form? - I keep forgetting which is which. -- Eddie Wyatt e-mail: edw@ius2.cs.cmu.edu terrorist, cryptography, DES, drugs, cipher, secret, decode, NSA, CIA, NRO.