views:

99

answers:

3

Hi

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.

+5  A: 

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
http://stackoverflow.com/questions/2975426/which-is-better-to-use-array-or-list
Gage
Care to explain why you think it cant be done? .NET supports an array of arrays, which is what the OP has asked about.
Jamiec
Compile time error, try it.. The second boundary must be supplied
Richard J. Ross III
+8  A: 

return new string[numRows][];

Itay
-1, causes compile time error
Richard J. Ross III
Compiles OK for me! Using Visual Studio 2008 and .NET 3.5.
CesarGon
It does compile.
Itay
It compiles fine for me.
Jackson Pope
This is indeed what the OP asked for and the right solution imo. +1 (any yes it compiles)
BrokenGlass
+2  A: 

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
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
Exactly........
CesarGon