Multidimensional Array [][] vs [,] [duplicate] - c#

This question already has answers here:
Differences between a multidimensional array "[,]" and an array of arrays "[][]" in C#?
(12 answers)
Closed 9 years ago.
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];

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

double[][] are called jagged arrays , The inner dimensions aren’t specified in the declaration. Unlike a rectangular array, each inner array can be an arbitrary length. Each inner array is implicitly initialized to null rather than an empty array. Each inner array must be created manually: Reference [C# 4.0 in nutshell The definitive Reference]
for (int i = 0; i < matrix.Length; i++)
{
matrix[i] = new int [3]; // Create inner array
for (int j = 0; j < matrix[i].Length; j++)
matrix[i][j] = i * 3 + j;
}
double[,] are called rectangular arrays, which are declared using commas to separate each dimension. The following piece of code declares a rectangular 3-by-3 two-dimensional array, initializing it with numbers from 0 to 8:
int [,] matrix = new int [3, 3];
for (int i = 0; i < matrix.GetLength(0); i++)
for (int j = 0; j < matrix.GetLength(1); j++)
matrix [i, j] = i * 3 + j;

double[,] is a 2d array (matrix) while double[][] is an array of arrays (jagged arrays) and the syntax is:
double[][] ServicePoint = new double[10][];

double[][] is an array of arrays and double[,] is a matrix. If you want to initialize an array of array, you will need to do this:
double[][] ServicePoint = new double[10][]
for(var i=0;i<ServicePoint.Length;i++)
ServicePoint[i] = new double[9];
Take in account that using arrays of arrays will let you have arrays of different lengths:
ServicePoint[0] = new double[10];
ServicePoint[1] = new double[3];
ServicePoint[2] = new double[5];
//and so on...

Related

I can't convert int[][] to int[,] and can't define an int[][] array

I am trying to solve a challenge on a coding site. The problem is about int matrixes. I am using c# language.I need to create a function that takes a parameter as int[][] (integer matrix) and also return int[][] (another integer matrix). Starting of problem (the empty function given to me) is like that
int[][] boxBlur(int[][] image) {
}
and this is what i tried so far
int[][] boxBlur(int[][] image) {
int pixelLength = image[0].Length - 2;
int[][] newBox = new int[pixelLength][pixelLength];
int pixelSum = 0;
int c = 0;
for(int t = 0; t<pixelLength; t++)
{
for(int i = 0; i<pixelLength; i++)
{
for(int j = t; j < 3 + t ; j++)
{
for(int k = i; k < i+3 ; k++)
{
pixelSum += image[j][k];
}
}
newBox[t][i] = pixelSum / 9;
}
}
return newBox;
}
Now i don't have any problem with algorithm, probably it will work but the problem is that i can't define an Array like int[][]. It gives an error like Cannot implicitly convert type int to int[][] and when i try to create this array like
int[,] newBox = new int[pixelLength,pixelLength];
it also gives error because it says the return type is wrong and i can't change the return type so i need to define a matrix exactly like int[][].
Is there any way to do it or do i need to try another way?
int[][] is a jagged array, or in other words, an array of arrays.
When you see a int[], you understand it as an array of integers. That is, every "slot" of the array holds and integer. An array of arrays is exactly the same, except that every slot holds an array.
Once you understand that, it should make perfect sense why the correct way to initialize your jagged array is:
int[][] newBox = new int[pixelLength][];
Now you've said that newBox is an array of int arrays: newBox[0] is of type int[], newBox[1] is of type int[], etc. Because the default value of an array, like any other reference type, is null, the value of newBox[0], newBox[1], etc. is null; you need to initialize each and every one of them.
The advantage of jagged arrays is, of course, that each int[] can be the size you wish, hence the name jagged array.
So what you are essentially missing, once you initialize your jagged array correctly, is initalizing each and everyone of the int[] arrays before using them. You can do this inside the adequate loop.
Carrying on from here should be easy.
An interesting test to verify if you've understood everything correctly is initalizing and correctly filling up all the values of the following type:
int[][][] myHeadHurtsArray;
int[][] and int[,] are two different things. The first is Jagged Array, the second is Multidimensional Array.
When initializing jagged array you can give only the array length, not the length of all the arrays in it:
int[][] newBox = new int[pixelLength][];
And insert new array each time:
newBox[index] = new int[size];

Why am I getting "Cannot implicitly convert type `char' to `char[][]'" here? [duplicate]

This question already has answers here:
Differences between a multidimensional array "[,]" and an array of arrays "[][]" in C#?
(12 answers)
Closed 9 years ago.
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];
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
double[][] are called jagged arrays , The inner dimensions aren’t specified in the declaration. Unlike a rectangular array, each inner array can be an arbitrary length. Each inner array is implicitly initialized to null rather than an empty array. Each inner array must be created manually: Reference [C# 4.0 in nutshell The definitive Reference]
for (int i = 0; i < matrix.Length; i++)
{
matrix[i] = new int [3]; // Create inner array
for (int j = 0; j < matrix[i].Length; j++)
matrix[i][j] = i * 3 + j;
}
double[,] are called rectangular arrays, which are declared using commas to separate each dimension. The following piece of code declares a rectangular 3-by-3 two-dimensional array, initializing it with numbers from 0 to 8:
int [,] matrix = new int [3, 3];
for (int i = 0; i < matrix.GetLength(0); i++)
for (int j = 0; j < matrix.GetLength(1); j++)
matrix [i, j] = i * 3 + j;
double[,] is a 2d array (matrix) while double[][] is an array of arrays (jagged arrays) and the syntax is:
double[][] ServicePoint = new double[10][];
double[][] is an array of arrays and double[,] is a matrix. If you want to initialize an array of array, you will need to do this:
double[][] ServicePoint = new double[10][]
for(var i=0;i<ServicePoint.Length;i++)
ServicePoint[i] = new double[9];
Take in account that using arrays of arrays will let you have arrays of different lengths:
ServicePoint[0] = new double[10];
ServicePoint[1] = new double[3];
ServicePoint[2] = new double[5];
//and so on...

How to get the length of row/column of multidimensional array in C#?

How do I get the length of a row or column of a multidimensional array in C#?
for example:
int[,] matrix = new int[2,3];
matrix.rowLength = 2;
matrix.colLength = 3;
matrix.GetLength(0) -> Gets the first dimension size
matrix.GetLength(1) -> Gets the second dimension size
Have you looked at the properties of an Array?
Length gives you the length of the array (total number of cells).
GetLength(n) gives you the number of cells in the specified dimension (relative to 0). If you have a 3-dimensional array:
int[,,] multiDimensionalArray = new int[21,72,103] ;
then multiDimensionalArray.GetLength(n) will, for n = 0, 1 and 2, return 21, 72 and 103 respectively.
If you're constructing Jagged/sparse arrays, then the problem is somewhat more complicated. Jagged/sparse arrays are [usually] constructed as a nested collection of arrays within arrays. In which case you need to examine each element in turn. These are usually nested 1-dimensional arrays, but there is not reason you couldn't have, say, a 2d array containing 3d arrays containing 5d arrays.
In any case, with a jagged/sparse structure, you need to use the length properties on each cell.
for 2-d array use this code :
var array = new int[,]
{
{1,2,3,4,5,6,7,8,9,10 },
{11,12,13,14,15,16,17,18,19,20 }
};
var row = array.GetLength(0);
var col = array.GetLength(1);
output of code is :
row = 2
col = 10
for n-d array syntax is like above code:
var d1 = array.GetLength(0); // size of 1st dimension
var d2 = array.GetLength(1); // size of 2nd dimension
var d3 = array.GetLength(2); // size of 3rd dimension
.
.
.
var dn = array.GetLength(n-1); // size of n dimension
Best Regards!
Use matrix.GetLowerBound(0) and matrix.GetUpperBound(0).
You can also use:
matrix.GetUpperBound(0);//rows
matrix.GetUpperBound(1);//columns

Set Inner Array in a Multidimensional Array in C#

I've created a multidimensional array and want to set the entire inner array equal to a separate (single dimensional) array. How can I do this, besides going through each position in the arrays and setting grid[row][val] = inputNums[val]?
int[,] grid = new int[20,20];
// read a row of space-deliminated integers, split it into its components
// then add it to my grid
string rowInput = "";
for (int row = 0; (rowInput = problemInput.ReadLine()) != null; row++) {
int[] inputNums = Array.ConvertAll(rowInput.Split(' '), (value) => Convert.ToInt32(value))
grid.SetValue(inputNums , row); // THIS LINE DOESN'T WORK
}
The specific error I'm getting is:
"Arguement Exception Handled: Array was not a one-dimensional array."
You are mixing "jagged" arrays (arrays of arrays) with multidimensional arrays. What you want to use is probably jagged arrays (because no one in his right mind would want to use md arrays :-) )
int[][] grid = new int[20][];
// ...
grid[row] = inputNums;
// access it with
grid[row][col] = ...
// columns of a row:
var cols = grid[row].Length;
// number of rows:
var rows = grid.Length;
A md array is a single monolithical "object" with many cells. Arrays of arrays are instead many objects: for a 2d jagged array, one object is for the row "structure" (the external container) and one is for each "row". So in the end with a jagged array you must do a single new int[20, 20], with a jagged array you must do a new int[20][] that will create 20 rows and 20 myArray[x] = new int[20] (with x = 0...19) one for each row. Ah... I was forgetting: a jagged array can be "jagged": each "row" can have a different number of "columns". (everything I told you is valid even for 3d and *d arrays :-) You only have to scale it up)

Dynamically created jagged rectangular array

In my project I have a lot of code like this:
int[][] a = new int[firstDimension][];
for (int i=0; i<firstDimension; i++)
{
a[i] = new int[secondDimension];
}
Types of elements are different.
Is there any way of writing a method like
createArray(typeof(int), firstDimension, secondDimension);
and getting new int[firstDimension][secondDimension]?
Once again, type of elements is known only at runtime.
Generics should do the trick:
static T[][] CreateArray<T>(int rows, int cols)
{
T[][] array = new T[rows][];
for (int i = 0; i < array.GetLength(0); i++)
array[i] = new T[cols];
return array;
}
You do have to specify the type when calling this:
char[][] data = CreateArray<char>(10, 20);
Well you can do this:
int[,] array = new int[4,2];
What you get is called a multidimensional array (4x2). Here is a nice article about multidimensional arrays.
The term jagged array usually refers to arrays, that have different second dimensions. For example take:
int[][] jagged = new int[2][];
jagged[0] = new int[5]; // 5 elements
jagged[1] = new int[1]; // 1 element
so this is not a 2x5 array, but a jagged array..
If:
You definitely want a jagged array, and not a multi-dimensional one as mOsa mentions.
You definitely need it to be of dynamic type at runtime, and not at compile time using generics as Henk mentions.
You can use Array.CreateInstance something like:
static Array CreateArray (Type t, int rows, int cols)
{
Array arr = Array.CreateInstance (typeof(Array), rows);
for (int i = 0; i < rows; rows++) {
arr.SetValue (Array.CreateInstance(t, cols), i);
}
return arr;
}
But are you sure you need this to by dynamic type at runtime?
As mOsa mentioned, if you want rectangular jagged array, then you are better off using a multi-dimensional array.
int[,] array = new int[dimension, dimension2];
will generate a rectangular array.
The reason to use a jagged array, is if you want to create an array with different secondary dimensions. A jagged array is really an array of arrays, where as a multi-dimensional array is a slightly different beast.

Categories

Resources