-2

Code snippet with error

I am trying to take the largest element from each nested array seen in the "array" and assign the largest numbers into a separate array, I am getting the out of bounds error as seen in the image and i'm out of ideas, can someone please help me out here?

  • 1
    this answers your question: [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 Jun 19 '22 at 04:14
  • Your current code “assumes” that the array dimensions are the same by using the same ending condition with… `arr.Length` … but the array looks like it is a 3x4 array. You may want to check each array dimension with `arr.GetLength(0)` and `arr.GetLength(1)`. – JohnG Jun 19 '22 at 04:23
  • Don't post pictures of code or error messages. Post them as text, formatted appropriately. We can't copy code from a picture if we want to test it or modify it. – user18387401 Jun 19 '22 at 04:30
  • As for the question, there are no "nested arrays". A 2D array is a single entity - a matrix - where every element is a peer. If you actually want nested arrays then you're talking about a jagged array, which would be declared `int[][]` rather than `int[,]`. If you have a 2D array then you at least have the concept of rows and columns, even though they don't exist as distinct entities, but there are definitely not nested arrays. It may look that way from the syntax used to initialise the variable but it is not the case. – user18387401 Jun 19 '22 at 04:33

1 Answers1

0

Multidimensional array length is the product of the lengths of all dimensions (ie. count of all elements in the multidimensional array). In your example, that’s 3*4 or 12. When your code loops to i = 3, the index operation is out of bounds.

use Array.Rank as the condition for your outer loop and the Array.GetLength(int) for inner loop:

for(var i = 0; i < arr.Rank; ++i)
    for(var j = 0; j < arr.GetLength(i); ++j)
        … arr[i,j] …

See Array.GetLength(int) doc

Moho
  • 15,457
  • 1
  • 30
  • 31