#132 – Arrays That Are Both Multidimensional and Jagged

Jagged arrays are different than multidimensional arrays.  Multidimensional arrays have a rank greater than one, with a separate indexer and a size for each rank.  Jagged arrays are just an array of arrays.

You can create an array which is both jagged and multidimensional.  Here’s an example (a two-dimensional array of arrays).

 // Multidimensional / jagged array.  E.g. store array
 //   of phone call objects for each day of the week,
 //   each hour of the day.
 PhoneCall[,][] weeklyCallLog = new PhoneCall[7, 24][];

 // Record 2 calls for Monday between 8-9 AM
 weeklyCallLog[1 ,8] = new PhoneCall[2];
 weeklyCallLog[1, 8][0] = thisCall;
 weeklyCallLog[1, 8][1] = thatCall;

Here’s another example (an array of two-dimensional arrays):

 // public enum ChessPiece { Empty, Knight, Rook, Etc };
 ChessPiece[][,] chessGame = new ChessPiece[100][,];
 chessGame[0] = new ChessPiece[8, 8];
Advertisements

#124 – Declaring and Instantiating Multidimensional Arrays

C# allows declaring arrays of more than one dimension.  Where a 1-dimensional array can be thought of as a simple list of elements, a 2-dimensional array can be thought of as a collection of elements organized into rows and columns.

Here are a couple of examples (remember that all arrays are 0-based):

 // 2-dimensional array
 int[,] hourlyTempsForWeek = new int[7, 24];
 hourlyTempsForWeek[2, 12] = 45;     // Tuesday, 12PM
 hourlyTempsForWeek[6, 23] = 30;     // Saturday, 11PM

 // 3-dimensional array, R/G/B values for each pixel on screen
 byte[, ,] pixelRGBValues = new byte[1024, 768, 3];
 pixelRGBValues[0, 0, 0] = 255;  // R value at (0,0)
 pixelRGBValues[0, 0, 1] = 0;    // G value at (0,0)
 pixelRGBValues[0, 0, 2] = 255;  // B value at (0,0)