Reputation: 21
I have some troubles using array containing user-defined type. A simple code goes like this:
struct MyType
a::Int64
b::Int64
end
MyArray = Array{MyType}(5)
MyArray[1].a = [1 2 3]
The compiler shows an error message "UnderRefError: access to undefined reference" Is this the problem due to there is no default constructor for MyType?
Upvotes: 1
Views: 207
Reputation: 8566
In fact, there is always a default inner constructor automatically defined by Julia if you don't explicitly define one. It's equivalent to :
julia> struct MyType
a::Int64
b::Int64
MyType(a,b) = new(a,b)
end
Note that, by running MyArray = Array{MyType}(5)
, you just construct an 5-element array whose eltype
should be MyType
. Julia still doesn't know what on earth those entries are, that's what the error is complaining about.
Take a look at the following example:
julia> a = Array{Complex}(5)
5-element Array{Complex{T<:Real},1}:
#undef
#undef
#undef
#undef
#undef
btw, I don't know what you mean to do with this line MyArray[1].a = [1 2 3]
, since a
is of type Int
, not Vector{Int}
.
Upvotes: 4
Reputation: 8512
This line doesn't make sense
MyArray[1].a = [1 2 3]
You got to write something like
MyArray[1] = MyType(4, 5)
because the first element of the MyArray
array isn't defined. MyArray[1].a
means you are trying to access the a
member of an undefined object. That isn't going to work.
If you want to create an initialized 5 element array of MyType objects you can do something like this instead.
fill(MyType(0, 0), 10)
Upvotes: 3