lundi 10 avril 2017

Index out of bounds for random.NextBytes

I'm using a function InitializeLetters to prepare the letters for the start of the typing game. It is supposed to prepare 5 random letters into array of type byte[], and after that, pass the values into array of type char[]. While this kind of implementation works, it often gives an array out of bounds error. Here is the function itself and the place where it is used. Any ideas about this error or how can I fix it? Increasing the size of buff[5] does not solve the problem.

private static void InitializeLetters(char[] chars)
        {
            byte[] buff = new byte[5];
            Random rand = new Random();
            rand.NextBytes(buff);
            string charspallete = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            for (int i = 0; i < 5; i++)
            {
                chars[i] = charspallete[buff[i] % 26 + 1];
            }
        }

And the function is called at the button start.

private void labelStart_Click(object sender, EventArgs e)
        {
            if (state == 0)
            {
                state = 1;
                labelStart.Text = "Stop";
                tmrMoving.Enabled = true;
                char[] chars = new char[5];
                InitializeLetters(chars);
                c1 = chars[0];
                c2 = chars[1];
                c3 = chars[2];
                c4 = chars[3];
                c5 = chars[4];
                labelPause.Show();
            }
}




Aucun commentaire:

Enregistrer un commentaire