padleyj - 1 year ago 81
Vb.net Question

Why does this fix the issue w/ my Jagged array?

Small preface, I'm not a pro- programmer, I'm actually a mechanical engineer who happens to know some programming, and this is my First question here, so please bear with me. I'm kind of just putting rough summary code instead of my actual code to keep things simple.

I have a jagged array in vb.net that i'm using to track how much of some given compounds are going through each "zone" where the zones are the first index of the jagged array. I've already initialized the array elsewhere with:

``````jagged_arr()() = new double(4)() {}
``````

and the first of the arrays is always set beforehand, ex:

``````jagged_arr(0) = {1, 2, 3, 4}
``````

So later on I'm trying to iterate through and process things on a zone by zone basis, essentially:

``````for z = 0 to 3
if z = 2
jagged_arr(z + 1) = jagged_arr(z)  'NOTE!!!

for r = 0 to jagged_arr(z + 1).getUpperBound(0)
'more calcs
jagged_arr(z + 1)(r) += 2
next
end if
next
``````

Instead of giving me the array i expect:

``````{{1, 2, 3, 4},
{1, 2, 3, 4},
{3, 4, 5, 6},
{3, 4, 5, 6},
{3, 4, 5, 6}}
``````

I get an array like this:

``````{{3, 2, 3, 4},
{3, 2, 3, 4},
{3, 4, 5, 6},
{3, 4, 5, 6},
{3, 4, 5, 6}}
``````

I'm pretty confused why that happened. I'm even more confused why it worked as intended after i replaced the line noted above (with NOTE!!!) with this:

``````jagged_array(z + 1) = new double(jagged_array(z).getUpperBound(0)) {}
for i = 0 to jagged_array(z + 1).getUpperBound(0)
jagged_array(z + 1)(i) = jagged_array(z)(i)
next
``````

Am I missing something here? I don't get why having each array initially copy the last is causing this odd behavior. Any help is appreciated!

By doing this what you really do is assigning a reference to that array meaning that `jagged_array(z + 1)` and `jagged_array(z)` now refers to the same sub-array.
When you change your code what you do is creating a new object (new array) and copy the initial content into it (Note there is `Array.Copy` for that) and consequently they don't refer to the same object meaning a modification through one say `jagged_array(z + 1)` don't alter the object referenced by `jagged_array(z)`