home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / listings / v_09_06 / 9n06020a < prev    next >
Text File  |  1991-02-17  |  2KB  |  87 lines

  1.  
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. main()
  6. {
  7.     void **alloc2da(size_t rows, size_t cols, size_t elemsize,
  8.         size_t elptrsize);
  9.     int rows = 0;
  10.     int cols = 0;
  11.     long **pl;
  12.     double **pd;
  13.     int i, j;
  14.  
  15.     while (rows < 1 || cols < 1) {
  16.         printf("Enter number of rows and columns: ");
  17.         scanf("%d %d", &rows, &cols);
  18.     }
  19.  
  20. /* allocate a 2D array of rows x cols long ints */
  21.  
  22.     pl = alloc2da(rows, cols, sizeof(long), sizeof(long *));
  23.     if (pl == NULL) {
  24.         printf("Can't allocate array of longs\n");
  25.         exit(1);
  26.     }
  27.  
  28.     printf("\nArray pl\n");
  29.     for (i = 0; i < rows; ++i) {
  30.         printf("Row: %2d", i);
  31.         for (j = 0; j < cols; ++j)
  32.             printf("  %p", &pl[i][j]);
  33.         putchar('\n');
  34.     }
  35.  
  36. /* allocate a 2D array of cols x rows doubles */
  37.  
  38.     pd = alloc2da(cols, rows, sizeof(double), sizeof(double *));
  39.     if (pd == NULL) {
  40.         printf("Can't allocate array of doubles\n");
  41.         exit(1);
  42.     }
  43.  
  44.     printf("\nArray pd\n");
  45.     for (i = 0; i < cols; ++i) {
  46.         printf("Row: %2d", i);
  47.         for (j = 0; j < rows; ++j)
  48.             printf("  %p", &pd[i][j]);
  49.         putchar('\n');
  50.     }
  51. }
  52.  
  53. /* not maximally portable for other than 2D arrays of char */
  54.  
  55. void **alloc2da(size_t rows, size_t cols, size_t elemsize,
  56.     size_t elptrsize)
  57. {
  58.     void **aryadr;
  59.     size_t i;
  60.  
  61.     aryadr = malloc(rows * elptrsize);
  62.     if (aryadr == NULL)
  63.         return NULL;
  64.  
  65.     for (i = 0; i < rows; ++i) {
  66.         aryadr[i] = malloc(cols * elemsize);
  67.         if (aryadr[i] == NULL)
  68.             return NULL;
  69.     }
  70.  
  71.     return aryadr;
  72. }
  73.  
  74. Enter number of rows and columns: 3 4
  75.  
  76. Array pl
  77. Row:  0  4AB2  4AB6  4ABA  4ABE
  78. Row:  1  4AC4  4AC8  4ACC  4AD0
  79. Row:  2  4AD6  4ADA  4ADE  4AE2
  80.  
  81. Array pd
  82. Row:  0  4AF2  4AFA  4B02
  83. Row:  1  4B0C  4B14  4B1C
  84. Row:  2  4B26  4B2E  4B36
  85. Row:  3  4B40  4B48  4B50
  86.  
  87.