Why are jagged arrays in C # defined in the opposite way?

Say I have a type called T. Now suppose I make an array of the type Tit gives me T[]. In code, this gives:

var myArray = new T[10];

With a length of 10. So, we see that this makes an array containing 10 type elements T. This works if T int, string, BinaryWriteror whatever the standard. But let Tis an array type, for example, int[]or string[].

Then, if we want to define an array of 10 elements of type T( int[]), it should give something like this:

var myArray = new int[][10];

Replacing Twith int[]in the previous example. But this gives a syntax error, because the correct syntax in C # is:

var myArray = new int[10][];

What if we followed the logic of the first example, should provide an array containing the number of undefined arrays containing 10 integers.

The same applies to any size of notched arrays:

var myArray = new int[][][10];

Wrong, because the syntactically correct way is:

var myArray = new int[10][][];

This is not a personal preference or discussion in code style, but just logic: why is the syntax different when defining arrays of array types than when we define arrays of something else?

+4
source share
2 answers

Thus, the initialization syntax reflects the access syntax.

var myArray = new int[NUM_ROWS][];
...
/* Initialize rows of myArray */
...
var x = myArray[0][5]; /* Should this be row 0, col 5; or row 5, col 0? */

It would be uninteresting to myArray[0][5]analyze how (myArray[5])[0], since the indices will be inverted from left to right, so myArray[0][5]we will analyze instead (myArray[0])[5].

, myArray[i][j], i , j myArray[i].

i 0 NUM_ROWS-1, var myArray = new int[NUM_ROWS][]. , - , - .

: , - , .

+6

new T[10] , 10 T. , new int[][10], . T , new int[][10]. , T , new T[10] .

, T DateTime, 10 , myArray[9].Day

T int[], 10 , T, : myarray[9][2465], , 9 2466 .

, .

A T[10] - 10 T. , T .

, , new T[10] var myArray = new int[][10];. ++ :

https://www.tutorialspoint.com/cplusplus/cpp_multi_dimensional_arrays.htm

jagged- ++, , , .

, :

A) new T[10]: 10, T

B) new T[10] T is int[]: 10, int .

C) new int[][10]: , , 10 .

D) new int[10][]: 10 , int .

, B D , B C .

+1

Source: https://habr.com/ru/post/1680669/


All Articles