Dynamic allocation of multi-d arrays
Chris Torek
chris at mimsy.UUCP
Fri Jun 23 11:42:10 AEST 1989
In article <8236 at batcomputer.tn.cornell.edu> cloos at 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 at mimsy.UUCP> (or <14617 at 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 at mimsy.umd.edu Path: uunet!mimsy!chris
More information about the Comp.lang.c
mailing list