Date: Fri, 4 Apr 1997 15:49:32 +0000 ( ) From: "Gurunandan R. Bhat" To: William Heymann Cc: djgpp AT delorie DOT com Subject: Re: Dynamic Allocation of Multidimensional Arrays In-Reply-To: <33448D13.664@ucsu.Colorado.edu> Message-Id: Mime-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII On Fri, 4 Apr 1997, William Heymann wrote: > I was wondering how do I make an multi-dimensional array that itilalizes > at run time without knowing any of the parameters. there are two ways that i know of heres the first, assuming that you want a two d array of size n X m of type int: ------------------------------------------------------------------ int **array; int i, n, m; array = (int **)malloc((unsigned int)(n * sizeof(int *))); for (i = 0; i < n; ++i) array[i] = (int *)malloc((unsigned int)(m * sizeof(int))); ------------------------------------------------------------------ you can now refer to an int in this array by a[j][k] with j = 1...m and i = 1...n. another way is by declaring a 1d array of size n*m and do the index book keeping yourself for example you can the a[j][k] mentioned above by a[j*n + k]. in one case the element is accessed by *(*(a + j) + k) and in the other case by *(a + (n*j + k)) i was around when two c purists were arguing on the relative merits of the two methods. i left and came back later to find them still at it ;) i have heard it argued that the second is faster but the first is elegant. i'll let you know if they come to a conclusion. ;) > So how do I make a dynamic two dimensional array in C++? use new instead of malloc hope this helps, gurunandan