From: "John M. Aldrich" Newsgroups: comp.os.msdos.djgpp Subject: Re: Dynamically declaring 2-d arrays Date: Mon, 09 Feb 1998 19:22:05 -0500 Organization: Two pounds of chaos and a pinch of salt. Lines: 46 Message-ID: <34DF9DAD.21C2@cs.com> References: <34DF9744 DOT C7CFDBFE AT ea DOT oac DOT uci DOT edu> NNTP-Posting-Host: ppp212.cs.com Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Precedence: bulk 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. Again, this is a basic C question and is not strictly relevant to DJGPP. However, in the interests of amity among the Usenet community, I'll answer anyway. :-) Arrays are stored contiguously in memory, starting from the first element, and going to the last. Multiple-dimensionality is an illusion that makes it easier for programmers to handle different types of arrays, but really the data is still stored the same way. In order to create a dynamically allocated multi-dimensional array, you can simply declare a pointer, allocate space for the # of columns x the # of rows, and then reference it in standard array notation. The only difference is that you cannot use multi-dimensional notation with a pointer. Instead, you must substitute the calculation that the compiler actually uses: /* int array[max_x][max_y] */ int *array; array = (int *) malloc( max_x * max_y * sizeof(int) ); /* array[x][y] = 10 */ *(array + x * max_y + y) = 10; /* or */ array[x * max_y + y] = 10; If you really want to access the array in [][] notation, then you would have to create an array of pointers-to-int (or a pointer-to-pointer-to-int), and allocate first the space for the array, and second the space for each subarray. Such a pointer cannot be treated like a normal array in terms of memory, but can be accessed using the [][] notation (I think). After this it gets kind of complex, but can still be done. -- --------------------------------------------------------------------- | John M. Aldrich | "Always listen to experts. They'll | | aka Fighteer I | tell you what can't be done, and why.| | mailto:fighteer AT cs DOT com | Then do it." | | http://www.cs.com/fighteer/| - Lazarus Long | ---------------------------------------------------------------------