Page 1 of 1

Possible array copy bug?

Posted: Sat May 06, 2006 5:26 pm
by mouse
If you copy an array without specifying the element (ie a2()=a1() ) then both arrays point to the same memory space, so if you subsequently change either array both are updated.

Not sure if this should be a compile error, or if the array contents should be copied (which would be nice :D )

Code: Select all

Dim a1.l(10)
Dim a2.l(10)

OpenConsole()

;initialize arrays
For i = 1 To 10
  a1(i) = i + 100
  a2(i) = i + 200
Next i

PrintN("Initialized...")

;show the array values
For i = 1 To 10
  PrintN("a1("+Str(i)+") = "+Str(a1(i))+" : a2("+Str(i)+") = "+Str(a2(i)))
Next i

a2()=a1()
a1(5) = 55555
a2(7) = 77777

PrintN("")
PrintN("a2()=a1(), a1(5) and a2(7) changed...")

;show the array values
For i = 1 To 10
  PrintN("a1("+Str(i)+") = "+Str(a1(i))+" : a2("+Str(i)+") = "+Str(a2(i)))
Next i

Print("Hit <RETURN> to exit")
Input()

CloseConsole()

Posted: Sat May 06, 2006 6:11 pm
by Psychophanta
Hi,
that's a normal behaviour, and not a bug,
because when you refer to a2() or a1() you are referring to the base pointer of the array, so then if you do a2()=a1() you are assigning the base of a2() array to the a1() one.
It is the same as do: a2()=@a1()

Posted: Sun May 07, 2006 1:58 am
by mouse
I see what you're saying here Psychophanta, but in my opinion it seems a little inconsistant (and as far as I've seen undocumented). For example, as in the code below, you can't do the same with a structure.

BTW this isn't a gripe, it's just a personal thought! :?

Code: Select all

Structure st
  a.l
  b.l
EndStructure

x.st
y.st

x\a = 1
x\b = 2

y = x     ;this line won't compile

Posted: Sun May 07, 2006 8:30 am
by Psychophanta
Hi, mouse.
It should be done like that:

Code: Select all

Structure st 
  a.l 
  b.l 
EndStructure 

*x.st=AllocateMemory(SizeOf(st))
*y.st=AllocateMemory(SizeOf(st))

*x\a = 1 
*x\b = 2 

*y = *x

Debug *y\b