Multidimensional Array [][] vs [,] [duplicate]
double[][] ServicePoint = new double[10][9]; // <-- gives an error (1)
double[,] ServicePoint = new double[10,9]; // <-- ok (2)
What's their difference? (1) yields an error, what's the reason?
And
double d = new double[9]
ServicePoint[0] = d;
using (2) will prompt an error. Why?
One is an array of arrays, and one is a 2d array. The former can be jagged, the latter is uniform.
That is, a double[][]
can validly be:
double[][] x = new double[5][];
x[0] = new double[10];
x[1] = new double[5];
x[2] = new double[3];
x[3] = new double[100];
x[4] = new double[1];
Because each entry in the array is a reference to an array of double
. With a jagged array, you can do an assignment to an array like you want in your second example:
x[0] = new double[13];
On the second item, because it is a uniform 2d array, you can't assign a 1d array to a row or column, because you must index both the row and column, which gets you down to a single double
:
double[,] ServicePoint = new double[10,9];
ServicePoint[0]... // <-- meaningless, a 2d array can't use just one index.
UPDATE:
To clarify based on your question, the reason your #1 had a syntax error is because you had this:
double[][] ServicePoint = new double[10][9];
And you can't specify the second index at the time of construction. The key is that ServicePoint is not a 2d array, but an 1d array (of arrays) and thus since you are creating a 1d array (of arrays), you specify only one index:
double[][] ServicePoint = new double[10][];
Then, when you create each item in the array, each of those are also arrays, so then you can specify their dimensions (which can be different, hence the term jagged array):
ServicePoint[0] = new double[13];
ServicePoint[1] = new double[20];
Hope that helps!
In the first instance you are trying to create what is called a jagged array.
double[][] ServicePoint = new double[10][9].
The above statement would have worked if it was defined like below.
double[][] ServicePoint = new double[10][]
what this means is you are creating an array of size 10 ,that can store 10 differently sized arrays inside it.In simple terms an Array of arrays.see the below image,which signifies a jagged array.
http://msdn.microsoft.com/en-us/library/2s05feca(v=vs.80).aspx
The second one is basically a two dimensional array and the syntax is correct and acceptable.
double[,] ServicePoint = new double[10,9];//<-ok (2)
And to access or modify a two dimensional array you have to pass both the dimensions,but in your case you are passing just a single dimension,thats why the error
Correct usage would be
ServicePoint[0][2]
,Refers to an item on the first row ,third column.
Pictorial rep of your two dimensional array