Array out of bounds Euler 52

63 Views Asked by At

I've been trying to solve this problem on Euler. I want to convert an integer, to an array of strings. After this I want to convert each string to an array of characters, and this is where my code starts giving errors.

namespace Problem_52_Euler
{
    class Program
    {
        static void Main(string[] args)
        {
            for (uint i = 1; i < 1000000000; i++)
            {
                string[] xint = new string[i];                       
                char[] xArray = xint[i].ToCharArray();      // This line is going out of bounds              
                char[] yArray = xint[i + 1].ToCharArray();

                for (uint j = 0; j < xArray.Length; j++)
                {
                    char xInteger = xArray[j];
                    for (uint k = 0; k < yArray.Length; k++)
                    {
                        char yInteger = yArray[k];
                        if (xArray[0] == yArray[k] && xArray[0 + j] == yArray[k])
                        {
                            Console.WriteLine(" " + i);
                        }
                    }
                }
            }
        }
    }
}
1

There are 1 best solutions below

0
On

When you create an array with the length i, it will have indexes from 0 to i-1.

If i is for example 4, new string[i] will produce an array with the indexes 0, 1, 2 and 3. You can't access the item at index 4, because it doesn't exist.

Note: You don't need to convert a string to an array of character to access the characters, you can access the characters of a string just as if it was an array of characters.

Also, creating an array of strings doesn't create any strings, only room for references to the strings. If you just create the array and then try to get a string from it, you will get a null reference.