Page 58 - DCAP201_FUNDAMENTALS_OF_DATA_STRUCTURES
P. 58

Unit 4: Arrays




          Here is an example of defining an 8-by-8 array of integers, similar to a chessboard. Remember,  Notes
          because C arrays are zero-based, the indices on each side of the chessboard array run 0 through
          7, rather than 1 through 8. The effect is the same: a two-dimensional array of 64 elements.
          int chessboard [8][8];
          To pinpoint an element in this grid, simply supply the indices in both dimensions.
          If you have an m x n array, it will have m * n elements and will require m*n*element size bytes
          of storage. To allocate storage for an array you must reserve this amount of memory. The
          elements of a two-dimensional array are stored row wise. If table is declared as:
          int table [ 2 ] [ 3 ] = { 1,2,3,4,5,6 };
          It means that element
          table [0][0] = 1;
          table [0][1] = 2;
          table [0][2] = 3;
          table [1][0] = 4;
          table [1][1] = 5;
          table [1][2] = 6;
          The neutral order in which the initial values are assigned can be altered by including the groups
          in { } inside main enclosing brackets, like the following initialization as above:
          int table [2][3] = {{1,2,3}, {4,5,6}};
          The value within innermost braces will be assigned to those array elements whose last subscript
          changes most rapidly. If there are few remaining values in the row, they will be assigned zeros.
          The number of values cannot exceed the defined row size.
          int table [ 2 ][ 3 ] = { { 1, 2, 3},{ 4}};
          It assigns values as
          table [0][0] = 1;
          table [0][1] = 2;
          table [0][2] = 3;
          table [1][0] = 4;
          table [1][1] = 0;
          table [1][2] = 0
          Remember that, C language performs no error checking on array bounds. If you define an array
          with 50 elements and you attempt to access element 50 (the 51st element), or any out of bounds
          index, the compiler issues no warnings. It is the programmer’s task to check that all attempts to
          access or write to arrays are done only at valid array indexes.


               !
             Caution  Writing or reading past the end of arrays is a common programming bug and is
             hard to isolate.

          Let we understand that there is a standard way of drawing a two–dimensional m x n array A
          where the elements of A form a rectangular array with m rows and n columns where the
          element A[J, K] appears in row J and column K.







                                           LOVELY PROFESSIONAL UNIVERSITY                                   51
   53   54   55   56   57   58   59   60   61   62   63