首页 > 解决方案 > 将项目添加到数组时,索引超出了数组的范围

问题描述

这是我的代码

public static int[] MoveZeroes(int[] arr)
    {
        // TODO: Program me
        int zeroCount = 0;
        int[] temp = { };
        int numberItems = 0;
        foreach (var a in arr)
        {

            if (a == 0)
            {
                zeroCount += 1;
            }
            else
            {
                temp[numberItems] = a;
            }

            numberItems += 1;

        }
        return new int[] { };
    }

我用它喜欢

   int[] f = MoveZeroes(new int[] {1, 2, 1, 1, 3, 1, 0, 0, 0, 0});

但这给了我Index was outside the bounds of the array在线错误

temp[numberItems] = a;

如何在数组中添加项目?我究竟做错了什么 ?

标签: c#arrays

解决方案


int[] temp = { }

这将创建一个长度为 0 个元素的整数数组。您无法插入其中,因为它的长度为 0。

使用 a List<int>,您可以动态添加到它:

public static int[] MoveZeroes(int[] arr)
{
    // TODO: Program me
    int zeroCount = 0;
    var temp = new List<int>();
    int numberItems = 0;
    foreach (var a in arr)
    {

        if (a == 0)
        {
            zeroCount += 1;
        }
        else
        {
            temp.Add(a);
        }

        numberItems += 1;

    }
    return temp.ToArray();
}

推荐阅读