Saber Jalilzadeh
Saber Jalilzadeh

Reputation: 75

How to assign a value to an index of a three dimensional array?

I have defined two three dimensional arrays as:

int[, ,] Link_k = new int[length1, length1, length1];
int[][][] Link_k2 = new int[length1][][];

where length1 is variable and could be any integer number.

My question is that how could I assign a value for a special index or for all first indices. I tried

Link_k.SetValue(-1,(0,,));
Link_k2.SetValue(-1,[0][][]);

But that does not compile.

Upvotes: 0

Views: 74

Answers (2)

Patrick Hofman
Patrick Hofman

Reputation: 156968

If you want to set the first index of every Z-axis array, you have to iterate over it, using for for example.

For Link_k:

for (int x = 0; x < Array.GetUpperBound(Link_k, 0); x++)
{
    for (int y = 0; i < Array.GetUpperBound(Link_k, 1); y++)
    {
        Link_k[x, y, 0] = -1;
    }
}

And for Link_k2:

int[][][] Link_k2 = new int[length1][][];

for (int x = 0; x < Link_k2.Length; x++)
{
    Link_k2[x] = new int[length1][];
    for (int y = 0; i < Link_k2[x].Length; y++)
    {
        Link_k2[x][y] = new int[length1];
        Link_k2[x][y][0] = -1;
    }
}

(Note you don't seem to assign the second and third array. Assign that in a for loop, so you assign every array in every array, etc. so I have put that in too)

Upvotes: 1

kͩeͣmͮpͥ ͩ
kͩeͣmͮpͥ ͩ

Reputation: 7846

As @Patrick Hofman said, Link_k is pretty easy:

Link_k[x, y, 0] = -1;

Or, using SetValue:

Link_k.SetValue( -1, x, y, 0 );

However, you don't actually create a three dimensional array for Link_k2 - you create a one dimensional array of arrays of arrays. E.g. Link_k2[0] is int[][], and, when it is initialised, Link_k2[0][0] is int[].

So, for Link_k2 you'd need to:

for (int x = 0; x < Link_k2.Length; x++)
{
    //create a new array of arrays at Link_k2[x]
    Link_k2[x] = new int[length1][];
    for (int y = 0; y < Link_k2[x].Length; y++)
    {
        //create a new arrays at Link_k2[x][y]
        Link_k2[x][y] = new int[length1];
        for (int z = 0; z < Link_k2[x][y].Length; z++)
        {
            Link_k2[x][y][z] = -1;
        }
    }
}

Upvotes: 1

Related Questions