开发者

Really basic C# array/loop confusion

开发者 https://www.devze.com 2023-04-09 19:59 出处:网络
I\'m doing a basic 2D array in C# and I\'ve got a bit of confusion. I\'m a lot more used to working with 1-based arrays, so 0-based arrays kind of mess up my head if you know what I mean.

I'm doing a basic 2D array in C# and I've got a bit of confusion.

I'm a lot more used to working with 1-based arrays, so 0-based arrays kind of mess up my head if you know what I mean.

blocks = new Block[15, 999];

for (int x = 0; x <= 15; x++)
{
    for (int y = 0; y <= 999; y++)
    {
        blocks[x, y] = new Dirt(terra开发者_C百科inTexture, new Vector2(x * 16, y * 16));
    }
}

So it's telling me I'm out of bounds of the array?

If the array is from

0-15, 0-999

Shouldn't a loop from 0-15, 0-999 work?


It's not. 999 is the length of the array. Thusly, it's from 0-998, and when you loop over it, you should be in the habit of using "less than" rather than "less than or equal" -- then it will tend to come out right.


You have 15 and 999 elements, but since arrays are 0-indexed, that means they run from 0-14 and 0-998, respectively.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号