Problem with matrices

Asked

Viewed 97 times

1

Well I’m starting to study the language C#, I have some experience in Java, in java we have a certain problem in matrix manipulation, because, although there is no pointer in the language itself, when it comes to matrices this fear ends up existing, because when copying a matrix A example: ( matrizA = matrizB ). The matrix A ends up receiving the pointer of the matrizB, this way everything that changes in matirzA will change in matrizB. First point wanted to know this problem also occurs in C#. I went to perform a test, but I objected to a very stupid problem right away that I don’t know what the mistake 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 you are giving this error : System.Indexoutofrangeexception: 'The index was outside the matrix boundaries. And I have no idea what I’ve done wrong.

  • The error happens because game[0,2] does not exist because they are two positions and the Dice in C# starts from 0 then goes up to 1 understood!

  • 2

    you created the matrix of tamano 2, and tried to put 3 numbers inside it, in the positions 0, 1 and 2.... can only 0 and 1

  • so it is: https://dotnetfiddle.net/YXJ7zJ . And, the fact of changing in one, also changing in the other, is not a problem, it is a feature because the value is passed by reference.

  • You might also think so, if you put 9 values then it’s a matrix 3x3 and not 2x2 because 3x3=9

1 answer

2

As I said in the commentary, there is no position regarding 2 (new int[0,2]) because the C# begins its content of 0 and in the case of your array waiter goes up to the 1.

Correct code through the instance new int[2,2]:

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

How to copy the data the way you did (jogo = teste;) is copied by reference, but could use the Array.Copy 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 only happens in the array that was intended.

Reference:

Reading

Browser other questions tagged

You are not signed in. Login or sign up in order to post.