-9

Can someone help me with this problem? So, at the lines 70 and 75 I put a new value in the array, but I got this error:

Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Application.Main () <0x41237d50 + 0x00729> in :0
[ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Application.Main () <0x41237d50 + 0x00729> in :0

Code:

http://pastebin.com/YtEv8Afk

Thanks!

Kusum
  • 501
  • 2
  • 11
  • 30

1 Answers1

0

Your code on the places where you get the exception:

num_players = num_players + 1;
Array.Resize(ref players, num_players);
players[num_players].Name = s;

The resize statement resizes your array into an array with indexes ranging from 0 to num_players-1. The highest index you can use is num_playes-1.

So you can expect an exception if you try to access players[num_players].

Resizing an array is a very expensive operation. Quite often people advise to use only arrays if you are certain that the size of the array never changes. In all other cases use List < Players >. You will never have to resize it, just add the elements, they will be added to the end of the list.

By the way I see something strange in your code:

for(int k = 0; k == num_players; k--)
{
     players[k] = players[k + 1];
}

So you start with k=0; do your stuff and do k--, giving you a value of k == -1. I hardly believe that is what you intended to do.

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116