spspli
spspli

Reputation: 3328

How to assign the size of a two dimensional array at run time?

I have a two dimensional array defined as this

int[,] array1 = new int[,]{{1,0},{3,5},{2,5},{8,7}}; 

or I can input any other two dimensional array as array1, maybe

array1 = new int[6,2]...

I want to define another array2 which is a two dimensional array too, and I need array2 has the same lengths on both dimensions as array1. I cannot define array2 as

new int[array1.GetLength(0), array1.GetLength(1)]

how could I define it? If I leave it as new int[,] when I run below code, I get out of index exception which I think the exception makes sense.

for (int i = 0; i < array1.GetLength(0); i++)
    for (int j = 0; j < array1.GetLength(1); j++)
    {
        if (array1[i, j] == -1)
            array2[i, j] = i+j;
    }

Upvotes: 0

Views: 178

Answers (1)

casey
casey

Reputation: 6915

You get the index exception because your new int[,] isn't at least as big as array1. Contrary to your claim, you can define array2 using the length of array1's dimensions. Use:

int[,] array2 = new int[array1.GetLength(0),array1.GetLength(1)];

This will set array2 to the same dimensions as array1 and any valid element of array1 will be valid for array2 and so you will not get index exceptions.

Upvotes: 2

Related Questions