Problem with arrays

1

Well I'm starting to study the C # language, I have a certain experience in Java, in Java we have a certain problem in array manipulation, because although there is no pointer in the language itself, when it comes to arrays this fear ends up, because when copying an array To example: (matrixA = matrixB). The matrix A ends up recreating the matrix pointer B, so everything that changes in matrix A will change in matrixB. First point wanted to know this problem also occurs in C #. I went to perform a test, but I aim a very stupid problem soon enough that I do not know what the error is.

 static void Main()
    {
        int[,] jogo = new int[2, 2];
        jogo[0, 0] = 1;
        jogo[0, 1] = 2; 
        jogo[0, 2] = 3;
        jogo[1, 0] = 4;
        jogo[1, 1] = 5;
        jogo[1, 2] = 6;
        jogo[2, 0] = 7;
        jogo[2, 1] = 8;
        jogo[2, 2] = 9;

        int[,] teste = new int[2, 2];

        jogo = teste;

        Console.WriteLine(teste[0,0]+"|"+ teste[0, 1]+"|"+ teste[0, 2]);
        Console.WriteLine(teste[1, 0] + "|" + teste[1, 1] + "|" + teste[1, 2]);
        Console.WriteLine(teste[2, 0] + "|" + teste[2, 1] + "|" + teste[2, 2]);

    }

For some reason it is giving this error: System.IndexOutOfRangeException: 'The index was outside the bounds of the array.' and I have no idea what I did wrong.

    
asked by anonymous 16.06.2018 / 15:41

1 answer

2

As I said in the comment, there is no position relative to 2 ( new int[0,2] ) because C# starts its index 0 and in the case of its % created_creation goes to the 1 .

Correct code through instance array :

static void Main()
{
    int[,] jogo = new int[2, 2];
    jogo[0, 0] = 1;
    jogo[0, 1] = 2;     
    jogo[1, 0] = 4;
    jogo[1, 1] = 5;
}

When copying the data the way you did ( new int[2,2] ) is copied by reference, but you could use jogo = teste; to copy only the values of the positions as follows:

static void Main()
{
    int[,] jogo = new int[2, 2];
    int[,] teste = new int[2, 2];
    jogo[0, 0] = 1;
    jogo[0, 1] = 2;
    jogo[1, 0] = 3;
    jogo[1, 1] = 4;

    Array.Copy(jogo, teste, 4);
}

From there, any change you make will only happen in the% w_th% that was intended.

16.06.2018 / 16:29