Mail Archives: djgpp/1998/02/09/21:31:46
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 |
---------------------------------------------------------------------
- Raw text -