Reputation: 13
Ok, I'm trying to search a two dimensional array using the Length property (I have to use this otherwise I'd just use GetLength() ). This array is randomly populated with a set number of rows and columns. It will ask the user for a number to search for and then it will search the array and return true or false AND send back the indexes of the row and column if that number is found.
I'm fairly confident in the code from the research I've done to get the for loop set properly, but currently I'm getting an error that says "Wrong number of indices inside []; expected 2" when I try to search the columns of the array.
I've looked this error up and from what I've found this should be the right setup. So, I'm not sure where my issue is with this loop, could someone take a look at let me know what step I'm missing?
Thanks!
int [,] math;
math = new int[3, 5]; //So you can see my array that is declared in main
static bool SearchArray(int search, int [,] array, out int row, out int coln)
{
row = -1;
coln = -1;
// search parameter is given from another method where it asks the user for a number to search for in the array.
for (int x = 0; x < array.Length; x++)
{
for (int y = 0; y < array[x].Length; y++) //error is here with the array[x] and continues to any reference I try to make similarly.
{
if (array[x][y] == search)
{
row = array[x];
coln = array[y];
return true;
}
}
}
return false
Upvotes: 0
Views: 2652
Reputation: 192
See this question for details of the differences between multidimensional arrays (as you are using here) and jagged arrays (arrays of arrays).
If you declare a multi-dimensional array like so:
int [,] math = new int[3, 5];
you must access values in it like this:
int value = math[1,2];
If you declare a jagged array, like this:
int[][] math = new int[3][];
math[0] = new int[5];
math[1] = new int[5];
math[2] = new int[5];
(Although typically the sizes of the sub-arrays would vary - hence jagged.) Then you access the values as:
int value = math[1][2];
For your particular problem, if using multidimensional arrays, you'll also need to use 'Array.GetLength', as in:
for (int x = 0; x < array.GetLength(0); x++)
to get the individual dimensions of the parts (as in this question). In your example '.Length' is giving you the total size of the array, not the length of the first dimension.
Upvotes: 1
Reputation: 307
You are mixing jagged arrays with multi-dimensional, actually with two dimensional arrays. The solution for two dim. arrays would be something like this:
static bool SearchArray(int search, int [,] array, out int row, out int coln)
{
row = -1;
coln = -1;
for (int x = 0; x < array.GetLength(0); x++)
{
for (int y = 0; y < array.GetLength(1); y++)
{
if (array[x,y] == search)
{
row = x;
coln = y;
return true;
}
}
}
return false
}
Upvotes: 0