Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!ucsd!ucbvax!galileo.berkeley.edu!jbuck From: jbuck@galileo.berkeley.edu (Joe Buck) Newsgroups: comp.lang.c++ Subject: Re: parameter[][] Message-ID: <37961@ucbvax.BERKELEY.EDU> Date: 3 Aug 90 18:37:18 GMT References: <1545@m1.cs.man.ac.uk> <26B9BF5A.7291@orion.oac.uci.edu> Sender: usenet@ucbvax.BERKELEY.EDU Reply-To: jbuck@galileo.berkeley.edu (Joe Buck) Lines: 42 jk@cs.man.ac.uk (John Kewley ICL) writes: > >One of our staff is whingeing about having to specify the size of all > >dimensions for a multidimensional array (beyond the first that is). > >Can anyone give me some good reasons why this is, so I can placate him. > >He claims that it can be done in C so why can't it be done in C++. eapu034@orion.oac.uci.edu (Carl F. Edman) writes: > For starters: This is in no way possible in C or C++ and couldn't be > as the following example might illustrate. > In one source-file: > char array[4][6][8]; (rest of example deleted -- you can't do it this way) Oh, you of little imagination. Of course it's possible. You can make an object that looks just like a 2-D array, and you can pass it around without worrying about the size. It can even be a triangular array and use half the storage. Here's the trick: double **mat_alloc (int nrows, int ncols) { double **t = new double* [nrows]; for (int i = 0; i < ncols; i++) t[i] = new double [ncols]; } When John Kewley's friend says "it can be done in C" this is probably what he means, except that malloc is used instead of new. The code is a lot easier to understand when written with new, though. Voila. Do the analogous thing for three dimensions. Now you can use the object created by this function as a multidimensional array and pass it around to various functions. In C++ you can get really fancy and create sparse matrix classes, by overloading the [] operator and making separate classes for rows, planes, etc. -- Joe Buck jbuck@galileo.berkeley.edu {uunet,ucbvax}!galileo.berkeley.edu!jbuck