C# C# Collections Arrays Multidimensional Arrays

Fredrik Rönnehag
Fredrik Rönnehag
2,341 Points

Looping through a 3D jagged array

Trying to follow the example for the jagged array, but I'm getting NullReferenceException for my second for loop.

            Cell[][][] threeDimensions = new Cell[100][][];

            for (int i = 0; i < threeDimensions.Length; i++)
            {
                threeDimensions[i] = new Cell[10][];

                for (int y = 0; y < threeDimensions[i].Length; y++)
                {
                    threeDimensions[i][y] = new Cell[10];

                    for (int x = 0; x < threeDimensions[x].Length; x++)
                    {
                        threeDimensions[i][y][x] = new Cell();
                    }
                }
            }
Steven Parker
Steven Parker
171,252 Points

It would be easier to analyze the issue with the entire project. To share that, make a snapshot of your workspace and post the link to it here.

Fredrik Rönnehag
Fredrik Rönnehag
2,341 Points

I did it in Visual Studios rather than workspace. I actually noticed the problem and fixed it myself, leaving the code here if someone else gets stuck :)

namespace Collections
{
    class Program
    {
        static void Main(string[] args)
        {
            Cell[][][] threeDimensions = new Cell[100][][];

            for (int i = 0; i < threeDimensions.Length; i++)
            {
                threeDimensions[i] = new Cell[10][];

                for (int y = 0; y < threeDimensions[i].Length; y++)
                {
                    threeDimensions[i][y] = new Cell[10];

                    for (int x = 0; x < threeDimensions[i][y].Length; x++)
                    {
                        threeDimensions[i][y][x] = new Cell();
                    }
                }
            }
     }

    class Cell
    {
        public string Contents { get; set; }
    }



}

1 Answer

Steven Parker
Steven Parker
171,252 Points

For the benefit of anyone who doesn't immediately spot the difference, the innermost "for" loop is missing a dimension and has an incorrect index in the conditional clause:

                    for (int x = 0; x < threeDimensions[x].Length; x++)     // original
                    for (int x = 0; x < threeDimensions[i][y].Length; x++)  // fixed