简体   繁体   中英

What is the difference between these two ways of declaring an array?

What is the difference between:

int [][] myArray;

and

int [,] myOtherArray;

The first is a jagged array: an array where each item in the array is another array

int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];

The second is a multidimensional array, aka a matrix.

int[,] array = new int[4, 2]; // create a 4 by 2 matrix

myArray is a jagged array , or an array of arrays. Each element of myArray is itself an int[] .

myOtherArray is a rectangular (or multidimensional ) array - a single object containing all the data directly.

Which you should use really depends on the situation. Sometimes it can be handy to have an array for each "row" of data (with the ability to replace whole rows, and have rows with different lengths), whereas at other times it makes sense to force a uniform layout.

I found the best way to understand it was to see a graphical representation of it =)

int[][] jagged = new int[3][];
jagged[0] = new int[1];
jagged[1] = new int[2];
jagged[2] = new int[4];

will look like this

[0] - [0]
[1] - [0][1]
[2] - [0][1][2][3]

while a two+ dimensional

int[,] twodimensional = new int[3,4]

will look like this

[0,0][0,1][0,2][0,3]
[1,0][1,1][1,2][1,3]
[2,0][2,1][2,2][2,3]

第一个是锯齿状阵列,另一个是多维 - 不同之处在于锯齿状阵列的元素可以具有不同的尺寸和大小。

Jagged array:

int [][] myArray;

Rectangular array:

int [,] myOtherArray;

Quote Comparing Rectangular and Jagged Arrays :

The structure of rectangular and jagged arrays is significantly different.

One-dimensional arrays have specific instructions in the CIL that allow them to be optimized for performance. Rectangular arrays do not have these instructions, and are not optimized to the same level. Because of this, it can sometimes be more efficient to use jagged arrays of one-dimensional arrays—which can be optimized—than rectangular arrays, which cannot. On the other hand, the programming complexity can be less for a rectangular array because it can be treated as a single unit, rather than an array of arrays.

This has to be a duplicate. One is a jagged array, one is a two-dimensional array. You should be able to take it from there.

Both statements declare uninitialized multi-dimensional arrays of ints. The first is a jagged array and the second is 2-dimensional.

You can initialize the 2-dimensional array at the same time as you declare it as follows:

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

OR,

int[,] array = new int[4, 2];

Refer to the official documentation :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM