padleyj padleyj - 1 year ago 81 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 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
end if

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)

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!

Answer Source

What happens when you do your change is in the first code you're assigning some "sub-array" to "another place".
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.
Another way to put it is both become an alias to access it and so any modification done through one is reflected to the object accessed by the other because they refer to the same thing.

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download