Partilhar via


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

Capture1

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.

Comments

  • Anonymous
    January 18, 2008
    PingBack from http://msdnrss.thecoderblogs.com/2008/01/18/the-differences-between-int-and-int/

  • Anonymous
    January 18, 2008
    I read in another msdn-blog some while ago that int[][] was much faster than int[,].

  • Anonymous
    January 18, 2008
    Possible (if you are talking about index access). However, faster is a relative term. If you have thousands of elements then it might matter, otherwise you should go with the DS which makes more sense from desgin/readability aspects...

  • Anonymous
    March 05, 2009
    "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." I think this is not true. What about int[,] ar = new int[2, 3]? It is rectangular, but not square. I think here you have to have the same number of items (space) in every row, and the same number of items in every column, but there is no connection between those numbers.