为什么数组大小声明中使用" 1 QUOT;作为第一索引? [英] Why does array-size declaration use "1" as the first index?
问题描述
东西我注意到了有关C#/ Java是这个看似(我此刻的)问题与数组大小的声明和数组大小的默认第一个指数不一致。
Something that I noticed about C#/Java is this seemingly (to me at the moment) inconsistent issue with array size declaration and the default first-index of array sizes.
在使用数组时,说你要创建一个新的整数数组大小 3
,它应该是这样的:
When working with arrays, say you want to create a new integer array size 3
, it would look like this:
INT [] newArray = INT新[3] {1,2,3};
共发现和可读性,对吧?
Totally find and readable... Right?
编程语言标准似乎决定了第一指数 0
。
The standard with programming languages seem to dictate that the "first" index is 0
.
根据这种逻辑,如果我感兴趣的是创建一个数组的大小 3
,我确实应该写这样的:
Using that logic, if I am interested in creating an array the size 3
, I should really be writing this:
INT [] newArray = INT新[2] {1,2,3};
等一下.. VS抛出一个错误,说数组初始化长度为2,预计
。
Wait a minute.. VS is throwing an error, saying an array initialize of length 2 is expected
.
所以这是在通过一个数组,数组大小声明循环的第一个索引不一致?前者采用 0
-th基于索引,第二一个 1
-th指数。
So there's an inconsistency with the first index in looping through an array and the array-size declaration? The former uses a 0
-th based index, and the second a 1
-th index.
这不是破坏游戏/改变以任何形式或方式,但我真的好奇,为什么这里有一个差异,还是地狱,如果这甚至是一个问题了(就像我说的,这不是游戏打破任何方式,但我很好奇,为什么它做这种方式)。
It's not game-breaking/changing in any form or way, but I'm genuinely curious why there's a discrepancy here, or hell, if this is even an issue at all (like I say, it's not game-breaking in any way, but I'm curious as to why it's done this way).
我可以在此刻想到的原因 1
-th基于索引将用于:
I can at the moment think of reasons why 1
-th based index would be used:
在一个for循环,你会使用< newArray.Length
,而不是< newArray.Length - 1
或< newArray.Length
。
In a for-loop you would use < newArray.Length
as opposed to < newArray.Length - 1
or < newArray.Length
.
与工作列表
S代表一段时间,然后回来尺寸的需求将要申报阵列抓住我有点措手不及。
Working with List
s for awhile and then coming back to size-needs-to-be-declared-arrays caught me a bit off-guard.
推荐答案
我想你混淆与长度的索引器。你想握住你的阵列,通过
I think you are confusing the indexer with the length. You want to hold three elements (or variables) in your array, denoted by
...new int[3]...
和在大括号中的元素是的值的不是指数。指数仍基于0。长篇是这样的:
and the elements in the curly brackets are the values, not the index. Index is still 0-based. Longform would look like this:
int[] newArray = new int[3];
newArray[0] = 1;
newArray[1] = 2;
newArray[2] = 3;
所以,你可以看到你的从零开始的索引,是因为它关系到你的int值[]。
So in that, you can see where your zero-based index is as it relates to the values of your int[].
这篇关于为什么数组大小声明中使用&QUOT; 1 QUOT;作为第一索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!