#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

#129 – Initializing Jagged Arrays

It’s possible to declare and initialize a jagged array all in one statement.  Here’s an example:

 int[][] nums2 = new int[3][] { new int[] { 1, 2, 3 }, new int[] { 4, 8 }, new int[] { 10, 20, 30, 40 } };

or

 int[][] nums2 = { new int[] { 1, 2, 3 }, new int[] { 4, 8 }, new int[] { 10, 20, 30, 40 } };

#128 – Accessing Elements in Jagged Arrays

Recall that elements in multi-dimensional rectangular arrays are accessed using an indexer for each dimension, separated by a comma (,):

 // Rectangular array
 int[,] nums1 = new int[2, 3];
 nums1[0, 2] = 20;    // Accessing elements in rectangular array
 nums1[1, 1] = 21;

Elements in jagged arrays are accessed using an indexer for each dimension, but with each indexer enclosed in its own pair of square brackets:

 // Jagged array
 int[][] nums2 = new int[2][];
 nums2[0] = new int[3];
 nums2[1] = new int[2];
 nums2[0][1] = 11;    // Accessing elements in jagged array
 nums2[1][0] = 10;

#127 – Declaring and Instantiating Jagged Arrays

It’s possible in C# to declare and instantiate jagged arrays. A jagged array is one that can have a different number of columns in each row (assuming the array is two-dimensional).  A jagged array can also be considered to be an array of arrays.

When you declare and instantiate a jagged array, you specify the size of only the first dimension.

// Jagged array - 3 elements, each of which is array of int
 int [][] nums2 = new int[3][];

After initialization, the jagged array consists of a one-dimensional array of arrays, with each element of the array initialized to null.

As a separate step, you can then initialize each element of the jagged array as a separate array, each of which can be a different size.

 nums2[0] = new int[4];
 nums2[1] = new int[2];
 nums2[2] = new int[10];