Cannot instantiate 2-D array with dynamic size - c#

I have created a class with a 2d integer array as a member. What I want, is for that member to be dynamically allocated as an x by x matrix when I instantiate a truck instance through the constructor. Here is my code:
public class truck
{
public int[][] mat;
truck(int x)
{
mat = new int[x][x];
for(int i=0;i<x;i++)
for(int j=0;j<x;j++)
mat[i][j]=0;
}
}
It is giving me the following error:
Invalid rank specifier: expected ',' or ']'
on this line: mat = new int[x][x];
Why is it giving me this error?

You can't initialize a jagged array like that. You have to initialize the first dimension first, and then initialize the elements:
mat = new int[x][];
//now you can do this:
mat[0] = new int[x];
...
Maybe you want a multidimensional array instead?
public int[,] mat;
...
mat = new int[x,x];

By using [][] you create an array of arrays. It means that each element of the first dimension contains an array.
That is why you need to initialize x arrays instead of just one.
You can do that by:
for (int i=0; i<x; i++) mat[i] = new int[x];
If you need to create just a two dimensional matrix, you can use int[,] instead of int[][]. In this case you would be able to initialize it like mat = new int[x,x]

Related

Why can't I create a multidimensional array of arrays?

My program involves a 2-dimensional board: Square[width,height]. Each Square contains a collection of Pieces.
In the presentation layer, I want to only present the collection of Pieces in each Square and represent each Piece with its string Name. I.e. string[][width,height].
Declaring string[][,] compiles with no problem but I can't initialize the variable:
string[][,] multiArrayOfArrays; //No problemo
multiArrayOfArrays = new string[][8,8]; //Generates errors
The following errors are generated for the second line:
CS1586 Array creation must have array size or array initializer
CS0178 Invalid rank specifier: expected ',' or ']' ModChess
CS0178 Invalid rank specifier: expected ',' or ']' ModChess
I'm currently using List<string>[,] as a workaround but the errors vex me. Why can I successfully declare a string[][,] but not initialize it?
Note: Using VS Community 16.0.4, C# 7.3.
string[][,] multiArrayOfArrays; //No problemo
Here you just declare variable of specific type.
multiArrayOfArrays = new string[][8,8]; //Generates errors
And here you actually create new object of specific type. It generates errors because this is invalid syntax for multidimentional array initialization.
You need to specify size for first dimension [] and then initialize each element of that array with string[,].
Think of it as array of arrays:
string[][,] multiArrayOfArrays; //No problemo
multiArrayOfArrays = new string[5][,];//create 5 elements of string[,] array
for (int i = 0; i < multiArrayOfArrays.Length; ++i)
{
multiArrayOfArrays[i] = new string[8,8];//actually fill elements with string[8,8]
}
or
string[][,] multiArrayOfArrays; //No problemo
multiArrayOfArrays = new string[][,]
{
new string[8,8],
new string[8,8],
new string[8,8],
};
Probably you want a string[,][] a.
string[,][] a = new string[3, 4][];
a[0, 0] = new string[10];
a[0, 1] = new string[4];
a[1, 0] = new string[6];
string s = a[0, 0][2];
You have a special case of a jagged array, where the first array is 2-dimensional. It contains one-dimensional arrays of different sizes as elements.
The ordering of the array brackets might seem wrong, as the element type is usually on the left side of the brackets; however, if you think about on how you want to access elements, then it makes sense. First, you want to specify the 2 coordinates of the 2-dimensional board, then the single index of the pieces collection.
According to Jagged Arrays (C# Programming Guide), int[][,] jaggedArray4 = new int[3][,] "... is a declaration and initialization of a single-dimensional jagged array that contains three two-dimensional array elements of different sizes."

How can I change an 2D array to a 2D list and then back to a 2D array again?

I thought searching SO would show me a hit regarding 2D lists to 2D arrays but it seems it's not as common as I had thought.
This is what I've got:
// init array
int[][] a = new int[10][10];
// change 2D array to 2D list
List<List<int>> b = a.Cast<List<int>>().ToList();
// change 2D list back to 2D array
???
How can I change b back to a 2D array? Also is the above correct?
Something like this:
List<List<int>> lists = arrays.Select(inner=>inner.ToList()).ToList();
int[][] arrays = lists.Select(inner=>inner.ToArray()).ToArray();
It's totally wrong. You can't get b in that way. And even the initialization is wrong. And in .NET there are two types of multidimensional arrays... True multidimensional arrays and jagged arrays...
Let's start... You are using a jagged array (I won't tell you what it's, or the difference, you didn't ask for it... if you need them, google for it)
int[][] a = new int[10][]; // see how you define it?
// Only the first dimension can be is sized here.
for (int i = 0; i < a.Length; i++)
{
// For each element, create a subarray
// (each element is a row in a 2d array, so this is a row of 10 columns)
a[i] = new int[10];
}
Now you have defined a 10x10 array jagged array.
Now a little LINQ:
You want a list:
List<List<int>> b = a.Select(row => row.ToList()).ToList();
you want back an array:
int[][] c = b.Select(row => row.ToArray()).ToArray();
The first expression means
foreach element of a, we call this element row `a.Select(row =>` <br>
make of this element a List `row.ToList()` and return it<br>
of all the results of all the elements of a, make a List `.ToList();`
The second is specular.
Now... Just out of curiosity, and if you had a true multidimensional array? then it was complex, very comples.
int[,] a = new int[10,10];
int l0 = a.GetLength(0);
int l1 = a.GetLength(1);
var b = new List<List<int>>(
Enumerable.Range(0, l0)
.Select(p => new List<int>(
Enumerable.Range(0, l1)
.Select(q => a[p, q]))));
var c = new int[b.Count, b[0].Count];
for (int i = 0; i < b.Count; i++)
{
for (int j = 0; j < b[i].Count; j++)
{
c[i, j] = b[i][j];
}
}
With a tricky (and horrible) LINQ expression we can "convert" a multidimensional array to a List<List<int>>. The road back isn't easily doable with LINQ (unless you want to use the List<T>.ForEach() that you shouldn't ever use, because it's not kosher, and then List<T>.ForEach() isn't LINQ)... But it's easily doable with two nested for ()

How to pass part of a two-dimensional array as parameter to a function?

I've got a two-dimensional array like this:
double[,] results = new double[100,100];
I'd like to pass every one dimensional part of the array to a function as a paremeter.
for (int i = 0; i < 100; i++){
cool_function (results[???], 10);
}
How do I do this in C#?
source
Jagged arrays are arrays of arrays. The elements of a jagged array are other arrays.
Declaring Jagged Arrays
Declaration of a jagged array involves two brackets. For example, the following code snippet declares a jagged array that has three items of an array.
int[][] intJaggedArray = new int[3][];
The following code snippet declares a jagged array that has two items of an array.
string[][] stringJaggedArray = new string[2][];
Initializing Jagged Arrays
Before a jagged array can be used, its items must be initialized. The following code snippet initializes a jagged array; the first item with an array of integers that has two integers, second item with an array of integers that has 4 integers, and a third item with an array of integers that has 6 integers.
// Initializing jagged arrays
intJaggedArray[0] = new int[2];
intJaggedArray[1] = new int[4];
intJaggedArray[2] = new int[6];
We can also initialize a jagged array's items by providing the values of the array's items. The following code snippet initializes item an array's items directly during the declaration.
// Initializing jagged arrays
intJaggedArray[0] = new int[2]{2, 12};
intJaggedArray[1] = new int[4]{4, 14, 24, 34};
intJaggedArray[2] = new int[6] {6, 16, 26, 36, 46, 56 };
You can't do it without copying the corresponding part of the array.
Otherwise, you can use a double[][]. To initialize:
double[][] results = new double[100][];
for(int i = 0; i < 100; i++)
results[i] = new double[100];
You could do this by using a jagged array Type[][] instead of Type[,]. In this case you can just pass array[index]. Otherwise you will have to either pass the two-dimensional array together with the index of the subarray of interest and perform the indexing in the called method or create a copy of the subarray of interest.
If you mean for an array myarray[x][y] that you want to call a function for x arrays of size y then all you need is the following code:
int i;
for (i = 0; i < 100; i++)
{
cool_function(array[i], 10);
}

How to make array in existing array's index, C#

How can I make array in existing array's index without using pointer for e.g
float[] currentNode = new float[12]
float[] neighbour = new float[12]
neighbour[8] = new float[12]
neighbour[8] = currentNode;
and can access with neighbour[8][1]
other option is something using pointers.
float *pointer;
int []array = new int[12];
pointer = &array[0];
neighbour[8] = pointer
so does first solution possible w/o changing my both arrays ? any other solutions ?? .
You are looking for Multidimensional arrays.
int[,] myArray;
myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}}; // OK
You can't do that.
You have an array of float values, not an array of arrays.
Which means you cannot assign one element in the array (which holds a float value) a value which is an array.
You'd have to redefine your variables as:
float[][] neighbour = new float[12][];
This will declare an array of arrays, which means each element of the neighbour array can hold arrays of different lengths, or no array (null-reference).
If you want to declare a matrix, you can do it like this:
float[,] neighbour = new float[12, 8];
You also could use generics:
List<List<float>> numbers = new List<List<float>>();
numbers.Add(new List<float>());
numbers.Add(new List<float>());
numbers[0].Add(2.3);
numbers[0].Add(5);
numbers[0].Add(8.74);
numbers[1].Add(6.8);
numbers[1].Add(9.87);
float aNumber = numbers[1][0]; //6.8
float anotherNumber = numbers[0][2]; //8.74

fill 3-dimensional array(jagged array) with point data

I do have a 3-dimensional matrix
private int[][][] Matrix
but I dont know how to fill this.
the first dimension is for my slices of a picture
the second for my x-values of one slice ad the 3rd slice for my y-values.
so das anybody know how to fill this arrays with some data for testing?
thanks
You can do something like this:
Matrix = new int[5][][]; // 5 slices
Matrix[0] = new int[3][]; // 3 x values for the first slice
Matrix[0][0] = new int[2]; // 2 y values for the first x value in the first slice
But I don't think that you should use something like this. It is very error prone.
I suggest something like this:
class Slice
{
public IList<XValue> XValues {get; set; }
}
class XValue
{
public IList<YValue> YValues {get; set; }
}
class YValue
{
// ...
}
var slices = new List<Slice>();
You can use array literals to create arrays of arrays of arrays:
private int[][][] Matrix = {
{
{1,2,3},
{4,5}
},
{
{1,2},
{3},
{4,5,6,7,8},
{9,10}
},
{
{1,2,3}
}
};
Note that this is a jagged array, so different subarrays can have different number of items. If you want a three dimensional matrix you might want the three dimensional array int[,,] instead of nested one dimensional arrays.

Categories