SiteBanner

The classic 1D array we've examined so-far is the 'string' - a one-dimensional array of elements type 'char'.  A trivial matter is to create a 1D array using elements of type 'int'.   'C' provides a way for us to create and manipulate multi-dimensional arrays:   2D, 3D and other structures (although anything past 3D may cause brain injury).  This installment reviews CHAR and INT 2D arrays. 

 

(right-click to download)

/* pgm25 source */

#include <stdio.h>

#define MAXROW 3
#define MAXCOL 2

enum {RET_ERR = -1, RET_OK};

int main(void) {
     int c;                     // VOODOO 'scanf()' fix
     int entrycount;
     int row;
     int col;

     char letrs[MAXROW][MAXCOL];     // 2-dimensional arrays, one of 'char'
     int nums[MAXROW][MAXCOL];      // ...the other of 'int'

     printf("\nPlease enter %d lines. This will populate a 'grid' of %d rows & %d columns\n", MAXROW * MAXCOL, MAXROW, MAXCOL);
     printf("Each line: LETTER <Space> NUMBER <Enter>\n\n");

     entrycount = 0;
     for (row = 0; row < MAXROW; row++)  {
           for (col = 0; col < MAXCOL; col++)   {
                 printf("Entry %d: ", ++entrycount);
                 scanf("%c %d", &letrs[row][col], &nums[row][col]);

                 while ((c = getchar()) != '\n' && c != EOF );              // VOODOO code for 'scanf()' fix
                 }
           }

     printf("\nResults:\n\n");
     for (row = 0; row < MAXROW; row++) {
          for (col = 0; col < MAXCOL; col++)
               printf("letrs[%d][%d] holds: %c\t nums[%d][%d] holds: %d\n", row, col, letrs[row][col], row, col, nums[row][col]);
          }

     printf("\n");
     return(RET_OK);
     }