+ 3
Multidimensional Array Initialization C#
Can someone explain what the [2, 2, 3] means when initializing the multidimensional array? Please break down what each number means, and if possible, what would it mean for [2, 3] or [2, 1, 7, 4]. Thanks! Code: https://code.sololearn.com/ctc1JcWlOeT8/?ref=app
9 Respuestas
+ 11
The differences between multi-dimensional and jagged arrays can be subtle for many new to C#.
For those interested in learning more, read on...
** Multi-dimensional (MD) Arrays: **
These are similar to defining a matrix or table with a fixed number of elements per dimension.
Examples:
A 3 x 4 grid is 2 dimensional, defined with 3 rows and 4 columns containing 12 elements.
A 3 x 3 x 3 cube is 3 dimensional, defined with 3 grids, each containing 3 rows and 3 columns for a total of 27 elements.
In both examples, once initialized, the number of elements and dimensions are fixed.
** Jagged Arrays: **
These contain references to instances of other arrays, which can each be of different sizes.
Therefore the innermost dimension of a jagged array in C# cannot be initialized with a dimension size. Rather, the innermost dimension is left empty until a reference to an array instance is assigned.
I highly recommend reviewing the following link:
https://www.pluralsight.com/guides/multidimensional-arrays-csharp
+ 10
~ swim ~ There is one minor correction to point out in your first answer.
int[,,] is used to declare a multi-dimensional array where the commas indicate the dimensions.
Multi-dimensional arrays are arrays of one dimensional arrays stored in continuous memory addresses.
Multi-dimensional arrays require the number of elements per dimension to be specified at the time of initialization. The number of elements can either be explicitly bounded when initialized:
= int [2, 2, 3]
or be inferred with initialized values:
= int[,,]{
{{1,2,3}, {4,5,6}},
{{7,8,9}, {10,11,12}},
}
or both:
= int[2,2,3]{
{{1,2,3}, {4,5,6}},
{{7,8,9}, {10,11,12}},
}
int[][][] would be used to declare a jagged array, which is an array of references to other arrays. These other arrays can be of different sizes, which is not possible with multi-dimensional arrays.
+ 9
~ swim ~ Brilliantly answered... Especially in the follow-up response with ascii visuals. 😉👌
+ 6
[2,2,3] means 2 elements/slices in the first dimension, 2 in the second dimension and 3 elements in the third dimension. This gives a total of 2*2*3=12 elements, which is the 'length' of the array.
+ 5
Take a look at these posts as well :
https://stackoverflow.com/questions/4648914/why-we-have-both-jagged-array-and-multidimensional-array
https://www.geeksforgeeks.org/c-sharp-jagged-arrays/
+ 2
~ swim ~ i see now, thanks!
+ 1
Sonic Oh ok, thanks!
+ 1
~ swim ~ so, if arr[2, 2, 3] = { { { 1, 2, 3 }, { 4, 5, 6 } }, { { 7, 8, 9 }, { 10, 11, 12 } } }, what would be x, y, and z? Also, in a table, if possible, what would this look like?
0
Hi