I’m trying to create a jagged array to replace my 3D array. My code is below.
public Structure[][][] jaggedArray = new Structure;
This error is being thrown,
“Invalid rank specifier: expected ‘,’ or ‘]’”
I assume my syntax is wrong, and that it’s thinking I’m trying to initialize a regular array. So my question would be, how would I initialize this array?
Your particular array would be initialized like this:
public Structure[][][] jaggedArray;
// [ ... ]
jaggedArray = new Structure[][];
for (int x = 0; x < Size; x++)
{
var tmp1 = jaggedArray[x] = new Structure[];
for (int y = 0; y < Size; y++)
{
var tmp2 = tmp1[y] = new Structure;
for (int z = 0; z < Size; z++)
{
tmp2[z] = new Structure(); // or whatever you want to initialize each value.
}
}
}
The “tmp” variables are not necessary but they will speed up the process in case of a large “Size”. Without the tmp variables you would always need to index every array cascade each time you access the innermost element.
Without “tmp” it would look like this:
for (int x = 0; x < Size; x++)
{
jaggedArray[x] = new Structure[];
for (int y = 0; y < Size; y++)
{
jaggedArray[x][y] = new Structure;
for (int z = 0; z < Size; z++)
{
jaggedArray[x][y][z] = new Structure(); // or whatever you want to initialize each value.
}
}
}