1

I'm trying to build a multi-dimensional array to store integer arrays.

Array[] TestArray = new Array[2];

for(int i = 0; i < TestArray.Length; i++)
{
   TestArray[i] = new int[5];
}

How do I go about accessing the newly created members of the Array? I am not sure how to access the newly created arrays in the array although I can see that they're properly created and stored when debugging in Visual Studio.

4
  • Why don't you use a List<List<int>> ? Commented Jul 10, 2013 at 14:42
  • Why are you not using a strongly type array for TestArray? Commented Jul 10, 2013 at 14:42
  • Did you look Multidimensional Arrays?? Commented Jul 10, 2013 at 14:43
  • I'll look up the difference between multidimensional and jagged arrays in a bit but is there an industry convention to not taking my initial approach? It seems like a valid approach as far as memory management and manipulation Commented Jul 10, 2013 at 15:10

5 Answers 5

12

If you want an array of integer arrays, then you should declare it as such:

int[][] testArray = new int[2][];

for(int i = 0; i < testArray.Length; i++)
{
   testArray[i] = new int[5];
}

Arrays of arrays are called Jagged Arrays (in contrast to Multidimensional Arrays).

Sign up to request clarification or add additional context in comments.

Comments

2

Here is how to access fourth item in the second array:

int value = ((int[]) TestArray.GetValue(1))[3];

Although you would have much less trouble working with jagged arrays:

int[][] TestArray = new int[2][];
for (int i = 0; i < TestArray.Length; i++)
{
    TestArray[i] = new int[5];
}

or multidimensional arrays:

int[,] TestArray = new int[2,5];

Comments

1

Cast the TestArray element as an int[].

Array[] TestArray = new Array[2];

for(int i = 0; i < TestArray.Length; i++)
{
   TestArray[i] = new [] { 2,3 };
}

var firstIndexOfFirstArray = ((int[])TestArray[0])[0];

Comments

1

T[][] is the syntax you are looking for.

int[][] test = new int[2][];  //Declaring the array of arrays.

for (int i = 0; i < test.Length; i++)
{
    test[i] = new int[5];  //Instantiating a sub-arrays.
    for (int x = 0; x < test[i].Length; x++)
        test[i][x] = x + i;  //Filling a sub-arrays.
}

foreach (var array in test)  //iterating over the array of arrays.
    Console.WriteLine("Array: " + string.Join(", ", array));  //using a sub-array
Console.ReadLine();

For more info: http://msdn.microsoft.com/en-us/library/2s05feca.aspx

Comments

0

If looking for integer array, try

int[][] testArray

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.