Page 1 of 1

Swap arrays

Posted: Wed Jun 23, 2010 3:22 pm
by Trond
I wish that Swap could be used with arrays, to simply swap the names/pointers to the array.

Re: Swap arrays

Posted: Wed Jul 21, 2010 4:27 pm
by JustinJack
Hey, it can...try this:

Code: Select all

Dim Test1(5)
Dim Test2(5)

For k = 1 To 5
    Test1(k) = k
Next

For k = 1 To 5
    Test2(k) = k + 5
Next

Debug "Before Swap:"
Debug "Test1:"
For k = 1 To 5
    Debug Test1(k)
Next
Debug #CRLF$
Debug "Test2:"
For k = 1 To 5
    Debug Test2(k)
Next

Swap @Test1(), @Test2()

Debug #CRLF$
Debug "After Swap:"
Debug "Test1:"
For k = 1 To 5
    Debug Test1(k)
Next
Debug #CRLF$
Debug "Test2:"
For k = 1 To 5
    Debug Test2(k)
Next
I haven't found it in the PureBasic help Library, but it's very handy, you can assign arrays pointers too...like this:

Code: Select all


Procedure.l getMiscData()
    *myPtr = AllocateMemory(12)
      ; Set asside enough memory for three long integers (4 bytes ea.)
      PokeL(*myPtr, 123)
      PokeL(*myPtr+4, 456)
      PokeL(*myPtr+8, 789)
    ProcedureReturn *myPtr
EndProcedure

*thisPtr = getMiscData()

Dim myArray.l(MemorySize(*thisPtr)/4) ; same as Dim myArray.l(3)

myArray() = *thisPtr

For k = 0 To 2
    Debug myArray(k)
Next
FreeMemory(*thisPtr)

Hope it helps, I use it all the time..

Re: Swap arrays

Posted: Wed Jul 21, 2010 8:16 pm
by skywalk
@JustinJack, Your solution does not work for arrays passed to procedures, but will if the arrays are global.

This is an often discussed topic, and I would use it if implemented. :)