简体   繁体   中英

Index was outside the bounds of the array while adding item to array

Here is my code

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[] { };
    }

i use it like

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

But this is giving me error Index was outside the bounds of the array on line

temp[numberItems] = a;

how can i add items in array? what am i doing wrong ?

int[] temp = { }

This creates an array of ints that is 0 elements long. You can't insert into it because it has 0 length.

Use a List<int> and you can dynamically add to it:

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM