0

The code below is throwing an error at the beginning of the if statement. I believe it has something do with the character array, however I am not sure why that is. Any help would be much appreciated.

 public void display_bits(int count)
    {

        //bits that will be displayed

        string[] disp_bits = new string[1000]; 
        string[] disp_to_bits = new string[1000];

        int disp_count = 0;

        for (int i = 0; i <= count; i++)
        {
            char[] chars = { '~', '+', '*' };


            if (bits[i].IndexOfAny(chars) != 0)
            {

                bits[i] = disp_bits[disp_count];
                to_bits[i] = disp_to_bits[disp_count];
                disp_count++;

            }         
        }
    }
H H
  • 263,252
  • 30
  • 330
  • 514
Jimmy
  • 13
  • 3

1 Answers1

0

The bits string array doesn't appear to be initialized.

and

for (int i = 0; i <= count; i++)

might need changing to

for (int i = 0; i < count; i++)

So that your i index doesn't go outside the bounds of your array.

Matthew Cawley
  • 2,688
  • 1
  • 8
  • 19
  • I did that in the class. Its a global variable – Jimmy Jan 22 '17 at 17:20
  • And it's definitely initialized i.e using the `new` keyword? – Matthew Cawley Jan 22 '17 at 17:22
  • Yes, I initialized it in the begining of the class using the sytax below: string[] bits = new string[1000]; string[] to_bits = new string[1000]; – Jimmy Jan 22 '17 at 17:24
  • All of which was done in the beginning of the class I created – Jimmy Jan 22 '17 at 17:25
  • It could be that `for (int i = 0; i <= count; i++)` needs changing to `for (int i = 0; i < count; i++)` – Matthew Cawley Jan 22 '17 at 17:31
  • That seemed to fix the problem. Do you know why that is? – Jimmy Jan 22 '17 at 17:37
  • @Jimmy, you initialized only 218 elements? – Roman Jan 22 '17 at 17:39
  • @Roma So I initialized 1000, because I am going to use this software to parse various text files. I made the bits and to_bits string arrays in the beginning of the class, and passed in 218 because that was the length of the string array after parsing. – Jimmy Jan 22 '17 at 17:42
  • because `i` starts at 0, and you're using a raw `count` (that starts at 1) to terminate the loop. So if there are 1000 items and you say _"continue this loop whilst `i` is less than or equal to `1000`"_ it will loop 1001 times and on the 1001st iteration you won't have a string to operate against because the array doesn't hold that many. – Matthew Cawley Jan 22 '17 at 17:44
  • Ahh, I see. Thanks! – Jimmy Jan 22 '17 at 17:47
  • Most welcome. Don't forget to mark as answer if this was helpful. Thanks. – Matthew Cawley Jan 22 '17 at 17:50