-1

This is the code I have. I get an error on line 15 whne I enter any number. Combiantions of values I have tried for n and m include 4,5|9,9 etc.

int m = 0, n = 0;
int[,] arr = new int[n, m];

Console.WriteLine("value for n: ");
n = int.Parse(Console.ReadLine());
Console.WriteLine("\nvalue for m: ");
m = int.Parse(Console.ReadLine());

//giving arr values
Console.WriteLine("\nenter values for arr; ");
for (int i = 0; i < n; i++)
{
    for (int j = 0; j < m; j++)
    {
        arr[i, j] = int.Parse(Console.ReadLine());
    }
}

Exact error message

System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

Image: Image

I belive I know how multidimensional arrays work, however I might be missing something. Any help would be appriciated.

Samer
  • 11
  • 3
  • 1
    your `arr` is `int[0,0]` so ... yeah ... any index would be out of bounds – bolov Oct 14 '20 at 16:49
  • Duplicate: [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – Ňɏssa Pøngjǣrdenlarp Oct 14 '20 at 16:50
  • 2
    Basically: move your array initialization to *after* you've asked the user for `n` and `m`. This is a good example of why it's useful to declare variables only at the point where you can give them useful values - if you had `int n = int.Parse(Console.WriteLine());` and likewise for `m`, then you *couldn't* use them before they had appropriate values. – Jon Skeet Oct 14 '20 at 16:51
  • Well... I wont embares myself anymore than I already have. Thanks for pointing that out. I just overlooked it I gues – Samer Oct 14 '20 at 16:56

1 Answers1

1

You define your array as being n x m in terms of size. You set m and n as 0, making your array 0 in size. This means it is not able to hold any data.

Changing the values of m and n after the array has been declared does not increase the size of the array.

Thomas M
  • 192
  • 1
  • 1
  • 10