tags:

views:

324

answers:

8

Coming from a perl background, I have always defined a 2D array using int[][]. I know you can use int[,] instead so what are the differences?

+8  A: 

int[][] is an array of arrays or "jagged" array: you can use this when you want different sizes in the second dimension. For example, the first sub array can have 5 elements and the second can have 42.

int[,] is a two dimensional array: The second dimension is the same through out the array. With int[7, 42] the second dimension is 42 for all 7 lines.

jrcs3
Took the words right out of my mouth.
CptSkippy
+25  A: 

The difference here is that the first sample, int[][] creates a jagged array, while the second creates a multidimensional array (of dimension 2). In a jagged array each "column" can be of a different size. In a true multidimensional array, each "column" (in a dimension) is the same size. For more complete information see the Array section of the C# Programming Guide.

tvanfosson
+9  A: 

Here's a good comparison

Basically int[][] is a "jagged" array, it looks like this:

[] -> [1, 2, 3]
[] -> [1, 2]
[] -> [1, 2, 3, 4]

While int[,] is a multidimentional array which always has the same width and height:

[1, 2, 3, 4
 5, 6, 7, 8
 9, 1, 2, 3]

Each have their uses depending on what you're trying to accomplish.

Tom Ritter
Jagged--each 'row' can have different 'column' lengths. Multidimensional--each 'row' has the same 'column' length.
Will
+3  A: 

int[][] is a jagged array, where int[,] is a two dimensional array.

plainly

var a = int[][]

allows you do have an array like this:

a[0] = new int[2];
a[1] = new int[5];

where as with int[,] you must always have the second portion of the array be the same:

var a = int[2,2];

a[0,0]
a[0,1]
a[1,0]
a[1,1]

you can't have a[2,2];

Kevin
+3  A: 

int[][] is called an array of arrays, it can have arbitrary length for each row.

int[,] is called rectangular array, where all the rows have the same length. it Can be simulated by the first one.

AraK
A: 

One thing to consider about a jagged array is that you are allocating non-contiguous chunks of memory. This is a good thing if you have a large array of large objects. I've seen SomeThing[n,n] create StackOverflow issues, but SomeThing[n][n] be ok.

Also, if an object gets > 85,000 bytes it goes to the LOH (Large Object Heap). http://stackoverflow.com/questions/698147/net-collections-and-the-large-object-heap-loh

Andy_Vulhop
A: 

Here's an excellent article about arrays, covering this topic very well.

kek444
A: 

you can see int[][] as to (int[])[] (int[]) is a object

Edwin Tai