0
So what's the difference between a two-dimensional array, and a single-dimensional array of single-dimensional arrays? When to use which?
2 Antworten
+ 5
As the tutorial states:
A jagged array is an array-of-arrays, so an int[ ][ ] is an array of int[ ], each of which can be of different lengths and occupy their own block in memory.
A multidimensional array (int[,]) is a single block of memory (essentially a matrix). It always has the same amount of columns for every row.
+ 1
Hello. Think he means that
int[,] array = new int[2,2]
and
int[][] jaggedArray = new int[2][2]
are almost the same.
But have some differences in using. You can look at the example below
//2Dimensional array
int[,] array = new int[2, 2];
//set
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
array[i, j] = i * j + 1;
}
//get
Console.WriteLine("2Dimensional");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
Console.Write(array[i, j] + " ");
Console.WriteLine();
}
//Jagged array
int[][] jaggedArray = new int[2][] { new int[2], new int[2] };
//set
Console.WriteLine("Jagged");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
jaggedArray[i][j] = i * j + 1;
}
//get
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
Console.Write(jaggedArray[i][j] + " ");
Console.WriteLine();
}
Console.WriteLine("Arrays are equal: " + array.Equals(jaggedArray));
Console.WriteLine("2 Dimentional array has length = " + array.Length);
Console.WriteLine("Jagged array has length = " + jaggedArray.Length);
for (int i = 0; i < 2; i++)
{
Console.WriteLine(i + 1 + " array in Jagged array has length = " + jaggedArray[i].Length);
}
Console.WriteLine("2 Dimentional array has rank = " + array.Rank);
Console.WriteLine("Jagged array has rank = " + jaggedArray.Rank);
for (int i = 0; i < 2; i++)
{
Console.WriteLine(i + 1 + " array in Jagged array has rank = " + jaggedArray[i].Rank);
}
Console.ReadKey();
//Outputs
//2Dimensional
//1 1
//1 2
//Jagged
//1 1
//1 2
//Arrays are equal: False
//2 Dimentional array has length = 4
//Jagged array has length = 2
//1 array in Jagged array has length = 2
//2 array in Jagged array has length = 2
//2 Dimentional array has rank = 2
//Jagged array has rank = 1
//1 array in Jagged array has rank = 1
//2 array in Jagged array has rank = 1