Unfortunately your answer will lead to a serious problem if you change any one of the elements in matrix
. Say you assign matrix[0][0] = 1
, then matrix
will become something like
[
1, 0,0,0,0,0,0,0,0,0,0,0,0
1, 0,0,0,0,0,0,0,0,0,0,0,0
...
1, 0,0,0,0,0,0,0,0,0,0,0,0
]
Since you have repeated appended the same r
to matrix
, the underlying elements in matrix
is referencing the same memory block, i.e., matrix[0]
and matrix[1]
is pointing to the same memory block which is also referenced by var r
.
This is because r
is shallowly copied into matrix
. You should use deep copy instead.