Array Behavior

HI all,

I just noticed something with array behavior. It seems like a pair of arrays actually act like objects. Put this code in the open event of a window:

  Dim s1 as string = "FF,GG,GDKJ,GKDGHK,sjklj,askfh"
  
  Dim Array1() as string = s1.Split(",")
  Dim Array2() as String 
  
  Array2 = Array1
  
  Call Array1.Pop
  
  Break
  
  Call Array1.Pop
  
  Break
  
  Call Array2.Pop
  Break

You’ll notice in the debugger that BOTH arrays get decremented with each Pop. I did not know that arrays acted like objects this way in that setting Array2 = Array1 will basically point both arrays to the same memory location.

Is this expected behavior for arrays?

Jon

John - in depth discussion of the topic here: https://forum.xojo.com/12297-object-arrays-and-memory-leaks

this is right.
Arrays are objects and you have two variables pointing to same array.

If you want a true copy of the array, do something like this:

[code]Function copy_array(a() as String) As string()
dim new_array() as String
dim ub as integer = UBound(a)

ReDim new_array(ub)

//copy the array
for i as integer = 0 to ub
new_array(i) = a(i)
next

Return new_array

End Function[/code]

Then change your original code to:

[code] Dim s1 as string = “FF,GG,GDKJ,GKDGHK,sjklj,askfh”

Dim Array1() as string = s1.Split(",")
Dim Array2() as String

array2 = copy_array(Array1)

Call Array1.Pop

Break

Call Array1.Pop

Break

Call Array2.Pop
Break[/code]

And you should see the two arrays behave independently from one another.

You could also overload the “copy_array” function to handle different array types.

That said, this is code off the top of my head and I wouldn’t be surprised if there’s a more elegant solution.

I normally do the copy inline:

for each v as integer in Array1 Array2.append v next

For Each does not guarantee order.

Really? Why not?

it does not, but it’s from beginning to last since introduction. Maybe an implementation detail?

ah, the order for dictionary keys is not defined of course.

You’d have to ask the engineers, but that’s the way it’s documented. If you count on it being in order, you do so at your own risk.

Perhaps the new framework will be different.

if we ever wanted to make it possible to parallelize “for each” you could not guarantee order
that’s at least one reason