CopyStruct with a() = b() not copy?

Scubaticus

Active Member
Licensed User
I thought I could copy a structure with a() = b() but it seems only the pointer to a() is set to b()


A sample with two modules to illustrate:

Module A
B4X:
Sub Globals
   Public Type (A, B, C) aType(0)
End Sub

Sub App_Start
   form1.Show
   aType() = Array(("A", "B", "C"))
   initThis
End Sub

Public Sub initThis
   Button1.Text = aType(0).A
End Sub


Sub Button1_Click
   aForm.initThis
End Sub
Module B
Sub Globals
Dim Type (A, B, C) aType(0)
End Sub

Public Sub initThis
aForm1.Show
aType() = main.aType()

aType(0).A = "C"
aButton1.Text = aType(0).A

aForm1.Show
End Sub

Sub aButton1_Click
aForm1.Close
main.initThis
End Sub
After the aType(0).A = "C" in module B, the value of main.aType(0).A also becomes "C"

aType in Module A is declared public. aType in Module B is only ment to exist in module B


So is it possible to copy a structure?
 

Erel

Administrator
Staff member
Licensed User
If you want to create a new copy then you should use ArrayCopy.
However it only supports single dimension arrays or regular structs:
B4X:
Sub Globals
    Public Type (A, B, C) aType1
    Public Type (A, B, C) aType2
End Sub

Sub App_Start
    aType1() = Array("A", "B", "C")
    ArrayCopy(aType1(),0,3,aType2(),0)
    aType2.A = "AA"
    Msgbox(aType1.A,aType2.A)
End Sub
 

Scubaticus

Active Member
Licensed User
Thanks Erel,

The CopyArray will do. The reason I used a() = b() was because you mentioned it somewhere in the forum as an alternative way to copy an array.
 

Cableguy

Expert
Licensed User
Thanks Erel,

The CopyArray will do. The reason I used a() = b() was because you mentioned it somewhere in the forum as an alternative way to copy an array.
It dfoes work, if inserted in a for...next loop..

code:

for x = 0 to arraylen(a())-1
b(x)=a(x)
next
 

Cableguy

Expert
Licensed User
So it's posible after all! That's very nice but a little bit strange. Nice trick, thanks.
I believe it will also work for multi-dimensional array...
In that case the dimensions have to be filled one by one...

Code : (untested)

a(x,z) is a 2 dimension array.... declared as DIM a(100,50)
for x= 0 to 100 (1st dimension)
for z= o to 50 (2nd dimension)
b(x,z)=a(x,z)
next
next
 
Top