how to pass array(1) element of array(5,5) to a function in VB

Private Sub fun1()
    Dim array(5,5) As Integer
    For I As Integer = 0 To 4
        Function (array(I))
End Sub

I want to pass the arrays array(0), array(1), etc to Function(). But getting error:

Number of indices is less than dimensions of the indexed array



  • There are two ways of defining arrays in 2 dimensions in VB:

    1. Multidimensional arrays: Dim matrix(5, 5) As Integer
    2. Jagged arrays, i.e., array of arrays: Dim jagged As Integer()()

    The term "jagged" comes from the fact that every sub-array can have a different lengths. When creating the array, you can only specify the first dimension. The sub-arrays have to be created individually for each position of the main array.

    Dim jagged As Integer()() = New Integer(5)() {}
    jagged(0) = New Integer(5) {}
    jagged(1) = New Integer(5) {}

    Only in the second case you can select a one-dimensional array by specifying one index. For multidimensional arrays you must always specify two indexes and the result is always one "cell" (an Integer in this case).

    Now jagged(i) is a one dimensional array you can pass to your function.

    Another way to solve the problem is use a 2-d multidimensional array and pass the whole array plus a row number to your function. Then let your function loop through the columns of this row.

    Note also that in VB you specify the highest index when you create an array, not the size of the array. I.e., Dim array(5,5) as Integer is a 6 x 6 matrix, not a 5 x 5 matrix!

    See also: