1

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."

1 Answer 1

5

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.