Why does an array size declaration use "1" as the first index?

Something I noticed about C # / Java is apparently (in my opinion at the moment) an inconsistent problem with declaring the size of the array and the default with the first index of the size of the array.

When working with arrays, let's say you want to create a new array size by size 3, it will look like this:

int[] newArray = new int[3] {1, 2, 3};

Find and read completely ... Right?

The standard with programming languages, apparently, dictates that the "first" index 0.

Using this logic, if I am interested in creating an array of size 3, I really should write this:

int[] newArray = new int[2] {1, 2, 3};

Wait a minute. VS throws an error saying an array initialize of length 2 is expected.

So, is there inconsistency with the first index in the loop through the array and the declaration of the size of the array? The first uses the index 0-th, and the second a 1-th index.

This is not a game-violation / change in any form or method, but I'm really curious why there is a mismatch or hell, if this is a problem at all (for example, I say that this is not a game violation in any case, but I'm curious, why it is done that way).

At the moment, I can think of the reasons why the 1-th based index will be used :

In a for loop, you use < newArray.Lengthinstead of < newArray.Length - 1or < newArray.Length.

Working with Listfor some time, and then returning to arrays with the sizes needed for the declaration, made me tear myself a little.

+4
5

, . ( ) ,

...new int[3]...

- , . - 0. Longform :

int[] newArray = new int[3];
        newArray[0] = 1;
        newArray[1] = 2;
        newArray[2] = 3;

, , , int [].

+5

, .

, .

, 3 ? : 3 .

, "".

+15
int[] newArray = new int[2] {1, 2, 3};

: " , 2 , 3 ". ( , ) index , 0 C (, C, ++, #, Java, Javascript, Swift).

, ( , , C); . , arr[n] " arr, n * (the size of my type) . , n = 0, ( ).

+3

, Wim Hollebrandse, , , OP , 0 ( ) .

, . , , 1- 0- (.. 0)... , .

. , , 100 ( 4 ), , 100. 100 + 4 = 104 . 3- 2- 108.

, I- , 0, :

I-th-address = address_of_array + I * sizeof(datatype)
e.g. for our example it is 100 + i * 4

1, :

Ith-address - address of array + (I-1) * sizeof(datatype)

... , 0.

+2

. ( ), 3, . , index, 0. .

for < newArray.Length: 3, 0 0, 1 2. , 3 < lt; 3.

+1

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


All Articles