From: ian_d AT elric DOT accuris DOT ie (Ian Dunbar) Newsgroups: comp.os.msdos.djgpp Subject: Re: Dynamically declaring 2-d arrays Date: 12 Feb 1998 10:59:44 GMT Organization: Telecom Internet, Dublin, Ireland. Lines: 42 Message-ID: References: <34DF9744 DOT C7CFDBFE AT ea DOT oac DOT uci DOT edu> <34E1DFC4 DOT 76D102EF AT alcyone DOT com> NNTP-Posting-Host: 159.134.174.252 To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Precedence: bulk In article <34E1DFC4 DOT 76D102EF AT alcyone DOT com>, Erik Max Francis wrote: >Jason Alexander wrote: >> >> Can someone explain to me how to dynamically declare a 2-d array? >> I know the following code works for dynamically declaring a 1-d array >> of integers, but I don't see how to extend it to the 2-d case. > >The customary way is to allocate an array of pointers to int, and then >for each pointer to int, allocate an array of ints. It's a multistep >process, but what you end up with is a multidimensional array (you can >keep going if you want more than two dimensions) of arbitrary size that >can be indexed just like a statically declared one. > Just to add that it's not actually necessary to allocate separate blocks for each dimension. You can store all of the pointers in the same block as the data so long as you have allocated enough space for the pointers+the data and do the casting properly. It's a bit tricky to do but it's possible to generalize the step so you could have a function to allocate a N dimensional array in a single block, that would be called something like this: void *ndMalloc(size_t elementSize, int numDimensions, int *dimensions) or void *ndVaMalloc(size_t elementSize, int numDimensions, ...); The advantages being that you only need one call to free() to de-allocate the array, you can still use C syntax (i.e. array[1][2][3][4][5]) and also that you don't need to write a function for each array with a different number of dimensions. The disadvantages being the memory overhead, and the time it takes to initialize all of the pointers. Of course you should probably structure your code so that it can use the gcc feature for automatic arrays with variable size dimensions in a new block, and I think that that is usually possible to do that since a lot of "dynamic" arrays are not really very dynamic, you just don't know the sizes until run time. Ian ian_dunbar AT hotmail DOT com