[Gambas-user] Structure array, at second reading, always gives the value of the last element

ML d4t4full at gmail.com
Tue Aug 6 14:32:31 CEST 2019

On 6/8/19 08:05, vuott at tiscali.it wrote:
> Hello,
> I don’t understand why at the second reading of a Structure array I
> always get the value of the last element.
> |Public Struct AAAA   b As Byte   c As Short   i As Integer End Struct
> Public Sub Main()   Dim a As New AAAA   Dim aa As New AAAA[]   Dim i
> As Integer     For i = 0 To 7     aa.Push(a)     Valorizza(i, aa[i])  
>   Print aa[i].b,      ' first   Next Print Print   For i = 0 To 7    
> Print aa[i].b,      ' second   Next End Private Procedure Valorizza(c
> As Integer, s As AAAA)     s.b = 4 * c   End|
Looks like all the structs in the array refer (i.e: they're pointers) to
the same 'a' struct in the first DIM.
Therefore, when you change the value in ANY element, you end up changing
it in all elements just because they're all pointing to the same
original 'a'.

Change the first DIM to this:

|  Dim a As AAAA |

and alter the first FOR as follows:

|  For i = 0 To 7 a = New AAAA 'New line. This makes 'a' point to a new,
different structure in memory in each pass     aa.Push(a) 'continue your
original code here |

That fixes it.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.gambas-basic.org/pipermail/user/attachments/20190806/d2bbd068/attachment.html>

More information about the User mailing list