home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD2.mdf / c / library / dos / diverses / tctnt / arymult.c < prev    next >
Encoding:
C/C++ Source or Header  |  1991-08-27  |  1.6 KB  |  57 lines

  1. /* ARYMULT.C: Dynamically Allocated Multi-dimensional Arrays
  2. */
  3.  
  4. #include <stdio.h>        // for printf() and putchar()
  5. #include <stdlib.h>        // for exit()
  6. #include <alloc.h>        // for malloc()
  7.  
  8. #define ROW    10
  9. #define COLUMN 15
  10.  
  11. typedef int ARRAYTYPE;
  12. typedef ARRAYTYPE * ARRAYTYPEPTR;
  13.  
  14. //  Declare the 2D array as a pointer to a pointer to ARRAYTYPE.
  15. //  Note there is no memory allocated for the array yet.
  16. ARRAYTYPEPTR *array;
  17.  
  18. //*******************************************************************
  19. int main()
  20. {
  21.   int i, j;
  22.  
  23.   // 1st, allocate an array of pointers to ARRAYTYPE of ROW
  24.   // elements.  Next, looping through the array of pointers,
  25.   // allocate arrays of ARRAYTYPE of COLUMN elements and assign
  26.   // them to the pointers.  This assigns the necessary  memory
  27.   // to the array, which you can then index via the [] operators.
  28.  
  29.     array = (ARRAYTYPEPTR *) malloc (ROW * sizeof(ARRAYTYPEPTR));
  30.   if ( array == NULL ) {
  31.     printf("\nUnable to allocate memory! Exiting to DOS...");
  32.     exit(1);
  33.   }
  34.  
  35.   for (i = 0; i < ROW; i++) {
  36.     array[i] = (ARRAYTYPEPTR) malloc (COLUMN * sizeof(ARRAYTYPE));
  37.     if ( array[i] == NULL ) {
  38.       printf("\nUnable to allocate memory! Exiting to DOS...");
  39.       exit(1);
  40.     }
  41.   }
  42.  
  43.     // Fill array with unique values
  44.     for (i = 0; i < ROW; i++)
  45.         for (j = 0; j < COLUMN; j++)
  46.             array[i][j] = (COLUMN * i) + j;
  47.  
  48.     // Print out array to make sure everything's OK
  49.     for (i = 0; i < ROW; i++) {
  50.         for (j = 0; j < COLUMN; j++)
  51.             printf("%4d",array[i][j]);
  52.         putchar('\n');
  53.   }
  54.  
  55.   return 0;
  56. } // end of main()
  57.