2

I need to create 2D jagged array. Think of a matrix. The number of rows is known, the number of columns is not known. For example I need to create array of 10 elements, where type of each element string[]. Why do I need that? The number of columns is not known - this function must simply do the allocation and pass array to some other function.

string[][] CreateMatrix(int numRows)
{
 // this function must create string[][] where numRows is the first dimension.
}

UPDATE

I have C++ background. In C++ I would write the following (nevermind the syntax)

double ** CreateArray()
{
 double **pArray = new *double[10]() // create 10 rows first
}

UPDATE 2

I was considering using List, but I need to have indexed-access to both rows and columns.

Captain Comic
  • 15,744
  • 43
  • 110
  • 148

3 Answers3

8

return new string[numRows][];

Itay Karo
  • 17,924
  • 4
  • 40
  • 58
5

Cannot be done. However you could do something like this:

List<List<string>> createMatrix(int numRows)
{
     return new List<List<string>>(numRows);
}

That allows you to be able to have a flexible amount of objects in the second dimesion.

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
2

You can write:

string[][] matrix = new string[numRows][];

and that will produce a 2D array of null elements. If you want to fill the array with non-null items, you need to write:

for (int row = 0; row < numRows; row++)
{
    matrix[row] = new string[/* col count for this row */];
}

You need to specify the column count for each row of the matrix. If you don't know it in advance, you can either.

  1. Leave the matrix items unintialised, and populate them as you know their size.
  2. Use a fixed number that will give you room enough for the maximum possible size.
  3. Avoid arrays and use List<> as suggested by others here.

Hope this helps.

CesarGon
  • 15,099
  • 6
  • 57
  • 85
  • Thanks you Cesar, so I have two options for System.Array reference - either keep is set to null or set it some System.Array of known size. – Captain Comic Oct 07 '10 at 12:57