Domanda

Is there a way to access my three dimensional jagged array like this:

jaggedArray[1,2,3];

I got the following code snippets so far:

        int[][] jaggedArray = new int[3][]
        {
            new int[] { 2, 3, 4, 5, 6, 7, 8 },
            new int[] { -4, -3, -2, -1, 0, 1},
            new int[] { 6, 7, 8, 9, 10 }
        };

        int[,,] dontWork = new int[,,] // expect 7 everywhere in the last dimension
        {
            { { 2, 3, 4, 5, 6, 7, 8 } },
            { { -4, -3, -2, -1, 0, 1} },
            { { 6, 7, 8, 9, 10 } }
        };
È stato utile?

Soluzione

As for the first question, you're trying to access the 3rd element, of the 2nd element of the 1st element of the jagged array:

jaggedArray[1][2][3]

As for the error, a 3D array expects the same number of elements in each element of a dimension. Let's say, for simplicity's sake, that you have a 2D jagged array, a rough representation of what that looks like in memory would be:

First row  -> 2,   3,  4,  5, 6, 7, 8
Second row -> -4, -3, -2, -1, 0, 1
Third row  -> 6,   7,  8,  9, 10

You can see that each row is seen as a different array, and can therefore differ in size. A multidimensional array, however, does not have this property. It needs to be filled completely:

Column    :  0    1   2   3   4  5  6
------------------------------------
First row :  2,   3,  4,  5,  6, 7, 8
Second row: -4,  -3, -2, -1,  0, 1 
Third row :  6,   7,  8,  9, 10

Your table is missing some cells, which makes no sense. You need to use the same number of elements per dimension.

Altri suggerimenti

You got the syntax for declaring 2D jagged array right, 3D jagged arrays are an extension of that. For example:

int[][][] jagged3d = new int[][][]
{
    new int[][] { new int[] { 111, 112 }, new int[] { 121, 122, 123 } },
    new int[][] { new int[] { 211 } }
}

But to access it, you need different syntax:

jagged3d[0][1][2]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top