Array of integers falls after execution

0

I have an array of integers that must change its value every time a function executes it.

The problem arises every time it is executed, when going from number 1, it tells me Index was outside the bounds of the array

This is my code:

private const int n = 3;
private const int k = 4;
private static int[] workArr;


for (int i = 1; i <= 4; i++)
{
    int size = (int)Math.Pow(2, i);
    workArr = new int[i];  

    GenerateVariationsWithRep(i); //aqui es donde se cae y me muestra el error

}   



private static void GenerateVariationsWithRep(int length, int index = 0)
{           

    for (int i = 1; i <= n; i++)
    {
        workArr[index] = i; //selon el debug, me dice que aqui esta mal cuando index e i son iguales a 1
        GenerateVariationsWithRep(index + 1, length);
    }
}

What I look for is every time the function GenerateVariationsWithRep() is executed the array workArr changes and assigns the values 1,2 and 3.

How could I fix it?

Thanks

    
asked by A arancibia 08.06.2018 в 21:31
source

3 answers

0

I think the problem is when you set the size of the workArr array:

workArr = new int[i];

since, for example, when i = 1 the function GenerateVariationsWithRep(1) is executed and because n = 3 and the size of the array is 1, the error is generated. I think you should put:

workArr = new int[size];
    
answered by 08.06.2018 в 21:36
0

Arrays in C #, as in other languages, are based on zero. That means that the first item of it, is in the 0 position.

As you are asking to copy the value in position 1, in the first run it will fail.

Try putting an index equal to 0 and it will work (although not with much sense, you will always copy what you are going through first)

private static void GenerateVariationsWithRep(int length, int index = 0)
    
answered by 08.06.2018 в 21:36
-1

Why do not you use generics better List<int> tuMatriz =new List<int>() you take away all the problems

    
answered by 10.06.2018 в 03:45