0

I was trying to make a space invaders game using arrays to store the invaders, but each time I run the code it freezes and has the error about my array being the wrong size.

Error:

An unhandled exception of type 'System.OutOfMemoryException' occurred in mscorlib.dll

Can anyone please help? Here is my code:

class invaders
    {
        ingame game = new ingame();
        PictureBox[] spaceinvaders = new PictureBox[100];
        public void spawn(int level)
        {
            PictureBox invader = new PictureBox();
            Bitmap img = (WindowsFormsApplication1.Properties.Resources.SpaceInvader);
            for (int n = 1; n == 3 + level; n++)
            {
                for (int i = 12; i == 493; i = i + 37)
                {
                    invader = new PictureBox();
                    invader.Size = new Size(12, 12);
                    invader.Image = img;
                    spaceinvaders[i] = invader;

                    spaceinvaders[i].Location = new Point(i, n);
                }
            }
            game.Controls.AddRange(spaceinvaders);
        }
    }
5
  • Please give us the exact error message Commented Oct 14, 2017 at 10:49
  • An unhandled exception of type 'System.OutOfMemoryException' occurred in mscorlib.dll Commented Oct 14, 2017 at 10:51
  • On which line ? Commented Oct 14, 2017 at 10:59
  • Note that neither of the for loops in your example can even be entered since the base condition is respectively 1 == 3 + x and 12 == 943. You need to use the < sign in this case. Commented Oct 14, 2017 at 11:01
  • I changed == to < and it is the same error. The error says it is on a line in the designer bit of the form "this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));" is the line it is on Commented Oct 14, 2017 at 11:15

1 Answer 1

1

The condition for your for loops are wrong. You need to use the < sign instead of ==. The middle expression will be checked for each iteration and the loop execution will proceed only if the ouput of the check is true.

Since you ask the inner loop to go from 12 to 493, it does that. Except that 493 is more than 100 and thus the array is accessed outside of its bounds so you should get an "array out of bounds" exception.

I could not reproduce your error. Please fix your code so it is reproducible.

Sign up to request clarification or add additional context in comments.

2 Comments

How can I make it reproducible?
I have gotten the error to change to "An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll" saying that i need to make sure i don't have an infinite loop by changing all the "==" to "<="

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.