Search

Monday, January 14, 2008

The differences between int[,] and int[][]


Mumbai roadside drinks

A friend asked me the differences between the two. Here goes the answer

int[,]

This represents a two dimensional rectangular array. Let's take the following array definition

int[,] ar = new int[3, 3] { { 0, 1, 2}, 
{ 3, 4, 5},
{ 6, 7, 8}};

The array actually looks like the following



Which as we can see is rectangular. This kind of array is required when for every items represented in the rows there's exactly the same number of items represented in the column. E.g. a board game like chess.


int[][]


This is defined as array of arrays or as jagged arrays. They are created as follows

int[][] ar2 = new int[3][];
ar2[0] = new int[] { 0, 1, 2 };
ar2[1] = new int[] { 3, 4 };
ar2[2] = new int[] { 5, 6, 7, 8 };

The array looks like


Capture


Here the number columns is not the same for each row. A good example of this kind of usage is when we have a array of polygons where each row contains the coordinates of the vertices of the polygon. Since each polygon has different number of vertices (square, triangle, ...) this data-structure is useful in defining it.


Since it's jagged it has to be referenced carefully.

Console.WriteLine(ar2[0][2]); // Prints 2
Console.WriteLine(ar2[1][2]); // Crashes as row 1 has only 2 columns

The jagged array can be padded on the right to convert it to a rectangular array, but this will result in a lot of space wastage. In case of the jagged array the usage of space is sizeof(int) * 9 but if we pad it we will use sizeof(int) * max (column). This additional space can be significant.


Note:


int and 2D arrays were used only as example. This applied equally well to other data-types and higher dimensions.

No comments: