0

I'm using a 2D array to store data in a grid and all the data is ones and zeros. By default, the array is all zeros. When I attempt to modify values in the array using variable(y)(x) = 1 where x and y are integers in range it changes the value to 1 in the entire column, not just a single cell.

For example:

Public cells(19)() As Integer

'Code to  populate it with zeros goes here

Public Sub modifyCells(ByVal x As Integer, ByVal y As Integer)
    cells(x)(y) = 1
End Sub

Whenever I call modifyCells(0,0) I get the value of every sub-array looking like this:

1,0,0,0,0,0,0,0,0,0

Whereas I want this to happen only to the first sub array (i.e the value at cells(0)(0) = 1 and only that value).

How can I manage this? Thanks in advance.

(If it makes any difference the code used to populate the array is below)

Public Sub clear()
    Dim A1() As Integer = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
    For y = 0 To 19
        cells(y) = A1
    Next
End Sub
1
  • I think that's a 1D array containing 1D arrays, not a 2D array. A 2D array would be Dim x(19, 10) As Integer. As others have said, Commented Jan 3, 2011 at 21:09

2 Answers 2

1

Your problem is that you are populating each row with exactly the same array. You need to move your local variable definition into the loop:

Public Sub clear()
    For y = 0 To 19
        Dim A1() As Integer = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
        cells(y) = A1
    Next
End Sub
Sign up to request clarification or add additional context in comments.

Comments

0

You are basically adding a reference to the same array to each position in cells.

Try this instead:

Public Sub clear()
    For y = 0 To 19         
        cells(y) = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}     
    Next 
End Sub 

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.