I have an assignment for a class that is to be done in C#. Being a complete C# newbie, I did the project in Java first and I'm now trying to convert it to C#. I have the following function which results in the following compiler error.
Error: Invalid rank specifier: expected',' or ']' on the following line:
int[][] grid=new int[g.cols][g.rows];
Visual studio is underlining the g in g.rows
public int[][] getConvergenceCounts(MandelbrotGrid g){
int[][] grid=new int[g.cols][g.rows];
for(int x=0;x<g.cols;x++){
for(int y=0;y<g.rows;y++){
double tx=x*(double)3/400-1.5;
double ty=y*(double)3/400-1.5;
grid[x][y]=getConvergenceCount(new Complex(ty,tx));
}
}
return grid;
}
I have no idea what I'm doing wrong here and reading up on Multidimensional arrays in C# didn't seem to help.
The C# compiler thinks you're trying to declare a jagged array, and doing so incorrectly. A jagged array is an array of arrays, where each array contained within the main array can have a different number of elements. A jagged array is declared as follows:
int[][] jaggedArray = new int[numElements][];
Which would create an array that could hold "numElements
" arrays of integers within it.
You want to declare a multidimensional array, e.g.:
int[,] grid = new int[g.cols, g.rows];
public int[][] getConvergenceCounts(MandelbrotGrid g){
int[][] grid=new int[g.cols][];
for(int x=0;x<g.cols;x++){
int[x] = new int[g.rows]
for(int y=0;y<g.rows;y++){
double tx=x*(double)3/400-1.5;
double ty=y*(double)3/400-1.5;
grid[x][y]=getConvergenceCount(new Complex(ty,tx));
}
}
return grid;
}
If you want to use a jagged array the solution by @Frank is the method you need to do. You cannot declare both dimensions when you initiate a jagged array because the C# assumption is that your rows will have unequal dimensions. In @Doughnut's solution the multidimensional array method is a good solution if you have a matrix type solution (which this is), however C# is optimized for single dimensional arrays and you may still want to use the jagged array option in order to preserve time costs. For this reason, if you will be performing many operations on your multidimensional array you should initialize a jagged array THEN as you input your rows, specifying the row length individually.
public int[][] getConvergenceCounts(MandelbrotGrid g)
{
int[][] grid=new int[g.cols][];
for(int x=0;x<g.cols;x++){
grid[i] = new int[g.rows];
for(int y=0;y<g.rows;y++){
double tx=x*(double)3/400-1.5;
double ty=y*(double)3/400-1.5;
grid[x][y]=getConvergenceCount(new Complex(ty,tx));
}
}
return grid;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With