Possible array copy bug?

Just starting out? Need help? Post your questions and find answers here.
mouse
New User
New User
Posts: 9
Joined: Sun Mar 05, 2006 3:25 pm
Location: Isle of Wight, UK
Contact:

Possible array copy bug?

Post 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()
Win XP Pro 2002 SP2 : 1Gb memory : Sempron 3400+ : GeForce 6600 GT
Out of Chocolate Error - Reboot Universe.
User avatar
Psychophanta
Always Here
Always Here
Posts: 5153
Joined: Wed Jun 11, 2003 9:33 pm
Location: Anare
Contact:

Post 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()
http://www.zeitgeistmovie.com

while (world==business) world+=mafia;
mouse
New User
New User
Posts: 9
Joined: Sun Mar 05, 2006 3:25 pm
Location: Isle of Wight, UK
Contact:

Post 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
Win XP Pro 2002 SP2 : 1Gb memory : Sempron 3400+ : GeForce 6600 GT
Out of Chocolate Error - Reboot Universe.
User avatar
Psychophanta
Always Here
Always Here
Posts: 5153
Joined: Wed Jun 11, 2003 9:33 pm
Location: Anare
Contact:

Post 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
http://www.zeitgeistmovie.com

while (world==business) world+=mafia;
Post Reply