C# Jagged Arrays: An Array of Array
A jagged array is an array of array. Jagged arrays store arrays instead of literal values.
A jagged array is initialized with two square brackets [][]. The first bracket specifies the size of an array, and the second bracket specifies the dimensions of the array which is going to be stored.
The following example declares jagged arrays.
int[][] jArray1 = new int[2][]; // can include two single-dimensional arrays
int[][,] jArray2 = new int[3][,]; // can include three two-dimensional arrays
In the above example, jArray1
can store up to two single-dimensional arrays. jArray2
can store up to three two-dimensional, arrays [,] specifies the two-dimensional array.
int[][] jArray = new int[2][];
jArray[0] = new int[3]{1, 2, 3};
jArray[1] = new int[4]{4, 5, 6, 7 };
You can also initialize a jagged array upon declaration like the below.
int[][] jArray = new int[2][]{
new int[3]{1, 2, 3},
new int[4]{4, 5, 6, 7}
};
jArray[0][0]; //returns 1
jArray[0][1]; //returns 2
jArray[0][2]; //returns 3
jArray[1][0]; //returns 4
jArray[1][1]; //returns 5
jArray[1][2]; //returns 6
jArray[1][3]; //returns 7
You can access a jagged array using two for loops, as shown below.
int[][] jArray = new int[2][]{
new int[3]{1, 2, 3},
new int[4]{4, 5, 6, 7}
};
for(int i=0; i<jArray.Length; i++)
{
for(int j=0; j < (jArray[i]).Length; j++)
Console.WriteLine(jArray[i][j]);
}
The following jagged array stores two-dimensional arrays where the second bracket [,] indicates the two-dimensional array.
int[][,] jArray = new int[2][,];
jArray[0] = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };
jArray[1] = new int[2, 2] { { 7, 8 }, { 9, 10 } };
jArray[0][1, 1]; //returns 4
jArray[1][1, 0]; //returns 9
jArray[1][1, 1]; //returns 10
If you add one more bracket then it will be array of array of arry.
int[][][] intJaggedArray = new int[2][][]
{
new int[2][]
{
new int[3] { 1, 2, 3},
new int[2] { 4, 5}
},
new int[1][]
{
new int[3] { 7, 8, 9}
}
};
Console.WriteLine(intJaggedArray[0][0][0]); // 1
Console.WriteLine(intJaggedArray[0][1][1]); // 5
Console.WriteLine(intJaggedArray[1][0][2]); // 9
In the above example of a jagged array, three brackets [][][] means an array of array of array. So, intJaggedArray
will contain two elements, which means two arrays. Now, each of these arrays also contains an array (single-dimension). intJaggedArray[0][0][0]
points to the first element of first inner array. intJaggedArray[1][0][2]
points to the third element of the second inner array. The following figure illustrates this.