I tripped across something that I just plain don’t understand when using an array to contain a structure. If I have a structure created outside a for loop and try to assign it to an element of the array, I do not get the structure values in the array. Yet, if I create it in the for loop, it is assigned correctly.
My thought was to create a structure with an initial value, then assign it to all elements of the array–this did not work–the array elements where assigned some value which I have not idea where they came from.
I am wanting to understand how julia handles arrays of structures. I have pasted some test code below. Examples 1 and 3 work in that they give me the expected results; Example 2 gives me funky results.
I am running julia 1.4 on Linux Mate
Thanks.
----Code follows----
module TestArray
mutable struct Point # Attributes of each character on screen
X::Int64
Y::Int64
end
function PrintArray(pa::Array{Point})
global Point
for i in 1:length¶
x = pa[i].X
y = pa[i].Y
println(“i = $i, X = $x, Y = $y”)
end
end
Test case 1 – define array as a collection of structures
initialized as 1 – 10, 2 – 20, 3 – 30 …
println(“Structure as array collection”)
PointArray1 = [Point(i, i * 10) for i in 1:5]
PrintArray(PointArray1)
Test case 2 – define array as 5 undefined elements,
then initialize each element from a structure containing
2 – 20, 4 – 40, 6 – 60 …
N.B.: structure is defined OUTSIDE loop
println(“\nStructure outside loop”)
PointArray2 = Array{Point,1}(undef, 5)
fta = Point(0, 0)
println("fta = ", fta)
for i in 1:length(PointArray2)
fta.X = i * 2
fta.Y = i * 20
PointArray2[i] = fta
end
PrintArray(PointArray2)
Test case 3 – Similar to case 2, but structure is defined INSIDE loop with
3 – 30, 6 – 60, 9 – 90 …
println(“\nStructure inside loop”)
PointArray3 = Array{Point,1}(undef, 5)
for i in 1:length(PointArray3)
fta = Point(i * 3, i * 30)
PointArray3[i] = fta
end
PrintArray(PointArray3)
end
-------------Results----------------------
Structure as collection — expected results correct
i = 1, X = 1, Y = 10
i = 2, X = 2, Y = 20
i = 3, X = 3, Y = 30
i = 4, X = 4, Y = 40
i = 5, X = 5, Y = 50
Structure outside loop – Results do not match expectation
fta = Main.TestArray.Point(0, 0)
i = 1, X = 10, Y = 100
i = 2, X = 10, Y = 100
i = 3, X = 10, Y = 100
i = 4, X = 10, Y = 100
i = 5, X = 10, Y = 100
Structure inside loop – Expected results correct
i = 1, X = 3, Y = 30
i = 2, X = 6, Y = 60
i = 3, X = 9, Y = 90
i = 4, X = 12, Y = 120
i = 5, X = 15, Y = 150