Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# rows of multi-dimensional arrays

In the C# programming language, how do I pass a row of a multi-dimensional array? For example, suppose I have the following:

int[,] foo;
foo = new int[6,4];
int[] least;
least = new int[6];

for(int i = 0; i < 6; i++)
{
    least[i] = FindLeast(ref foo[i]);     //How do I pass the ith row of foo???
}

Also, could anyone explain to me the benefit of having rectangular and jagged arrays in C#? Does this occur in other popular programming languages? (Java?) Thanks for all the help!

like image 801
CodeKingPlusPlus Avatar asked Mar 06 '12 19:03

CodeKingPlusPlus


2 Answers

You can't pass a row of a rectangular array, you have to use a jagged array (an array of arrays):

int[][] foo = new int[6][];

for(int i = 0; i < 6; i++)
    foo[i] = new int[4];

int[] least = new int[6];

for(int i = 0; i < 6; i++)
    least[i] = FindLeast(foo[i]);

EDIT
If you find it so annoying to use a jagged array and desperately need a rectangular one, a simple trick will save you:

int FindLeast(int[,] rectangularArray, int row)
like image 173
BlackBear Avatar answered Oct 21 '22 20:10

BlackBear


You don't, with a rectangular array like that. It's a single object.

Instead, you'd need to use a jagged array, like this:

// Note: new int[6][4] will not compile
int[][] foo = new int[6][];
for (int i = 0; i < foo.Length; i++) {
    foo[i] = new int[4];
}

Then you can pass each "sub"-array:

int[] least = new int[foo.Length];
for(int i = 0; i < 6; i++)
{
    least[i] = FindLeast(foo[i]);
}

Note that there's no need to pass foo[i] by reference1, and also it's a good idea to assign local variables values at the point of declaration, when you can. (It makes your code more compact and simpler to understand.)


1 If you're not sure about this, you might want to read my article on parameter passing in C#.

like image 45
Jon Skeet Avatar answered Oct 21 '22 20:10

Jon Skeet