home *** CD-ROM | disk | FTP | other *** search
- /* ARYMULT.C: Dynamically Allocated Multi-dimensional Arrays
- */
-
- #include <stdio.h> // for printf() and putchar()
- #include <stdlib.h> // for exit()
- #include <alloc.h> // for malloc()
-
- #define ROW 10
- #define COLUMN 15
-
- typedef int ARRAYTYPE;
- typedef ARRAYTYPE * ARRAYTYPEPTR;
-
- // Declare the 2D array as a pointer to a pointer to ARRAYTYPE.
- // Note there is no memory allocated for the array yet.
- ARRAYTYPEPTR *array;
-
- //*******************************************************************
- int main()
- {
- int i, j;
-
- // 1st, allocate an array of pointers to ARRAYTYPE of ROW
- // elements. Next, looping through the array of pointers,
- // allocate arrays of ARRAYTYPE of COLUMN elements and assign
- // them to the pointers. This assigns the necessary memory
- // to the array, which you can then index via the [] operators.
-
- array = (ARRAYTYPEPTR *) malloc (ROW * sizeof(ARRAYTYPEPTR));
- if ( array == NULL ) {
- printf("\nUnable to allocate memory! Exiting to DOS...");
- exit(1);
- }
-
- for (i = 0; i < ROW; i++) {
- array[i] = (ARRAYTYPEPTR) malloc (COLUMN * sizeof(ARRAYTYPE));
- if ( array[i] == NULL ) {
- printf("\nUnable to allocate memory! Exiting to DOS...");
- exit(1);
- }
- }
-
- // Fill array with unique values
- for (i = 0; i < ROW; i++)
- for (j = 0; j < COLUMN; j++)
- array[i][j] = (COLUMN * i) + j;
-
- // Print out array to make sure everything's OK
- for (i = 0; i < ROW; i++) {
- for (j = 0; j < COLUMN; j++)
- printf("%4d",array[i][j]);
- putchar('\n');
- }
-
- return 0;
- } // end of main()
-