[comp.lang.c] Dynamic allocation of multi-d arrays

cloos@batcomputer.tn.cornell.edu (James H. Cloos Jr.) (06/22/89)

Hello,

Is it possible to dynamically allocate a multi-dimentional array using the
standard Unix libraries?  How is this done?

I believe I understand how to do single-d arrays, but haven't seen anything
suggesting how to do multi-d.  Or at least 2-D.

Do you have to set up a single-d array and use a pointer to specify the
beginning of the current 'row?'

I hope this isn't too much of a novice-mode question, but an application
I'm starting to work on is the first I've done that needs dynamic multi-d
arrays--unless I can come up with a better algorithm. ;^)

Thank you for any info!

-JimC
--
James H. Cloos, Jr.          "Entropy isn't what it used to be."
jhc@Crnlvax5.BITNET            --c/o Fortune @ batcomputer.UUCP
jhc@Vax5.CCS.Cornell.ED		 #include <std_disclaimers.h>
cornell!vax1!vax5.cit.cornell.edu!jhc@rochester.UUCP
B-7 Upson Hall, Cornell Univ., Ithaca, NY 14853   +1 607 272 4519
Urgent mail to: cloos@TcGould.TN.Cornell.EDU cloos@CrnlThry.BITNET
	    or: batcomputer!cloos@cornell.UUCP

chris@mimsy.UUCP (Chris Torek) (06/23/89)

In article <8236@batcomputer.tn.cornell.edu> cloos@batcomputer.tn.cornell.edu
(James H. Cloos Jr.) writes:
>Is it possible to dynamically allocate a multi-dimentional array using the
>standard Unix libraries?

Yes.

>Do you have to set up a single-d array and use a pointer to specify the
>beginning of the current 'row?'

No.  See article <17882@mimsy.UUCP> (or <14617@mimsy.UUCP>, which is
entirely contained within the former, but the latter was posted in November
1988 and has probably expired by now :-) ).

Essentially, the two easy methods to use are row vectors (allows
arbitrarily shaped matrices) and pointers to arrays (requires all but
the first dimension to be fixed).  The latter are less often useful,
and require declarations of the form

	data_type (*pointer)[DIM1][DIM2];	/* pointer to array */

This pointer can then point to an array (or suitably molded block of
memory from malloc()) which would normally be considered to have type

	data_type array[DIM0][DIM1][DIM2];	/* array */

Again, all but the first dimension must be fixed at compile time.

A third alternative is to do the matrix subscript arithemtic yourself:

	data_type *pointer;			/* simple pointer */
	/* if pointer = &array[0][0][0]: */
	... pointer[(i * DIM1 + j) * DIM2 + k] ...

which is yet another way to access something which might normally be
declared as in the line marked /* array */ above.  Here, as with
vectors of vectors of vectors (for 3-dimensional arrays), the dimensions
can vary at runtime.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain:	chris@mimsy.umd.edu	Path:	uunet!mimsy!chris