# References in Julia

Is it possible to change the contents of a vector by means of a pointer? Of course I am aware of the following:

``````julia> v = zeros(6);

julia> p = v
6-element Array{Float64,1}:
0.0
0.0
0.0
0.0
0.0
0.0

julia> p = 10
10

julia> v
6-element Array{Float64,1}:
10.0
0.0
0.0
0.0
0.0
0.0
``````

But what I want is to point to a different position than the first one. For example, I realized I can do the following, but I do not know if this is the correct approach:

``````julia> v = zeros(6);
julia> p = Ref(v)
Base.RefValue{Array{Float64,1}}([0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
julia> p[] = 1
1
julia> p[] = 6
6
julia> v
6-element Array{Float64,1}:
1.0
0.0
0.0
0.0
0.0
6.0
``````

Then, what happens if I want to point `p` to a different position than the first one of `v`. Is that even possible? In C would be something like:

``````p = &v;
p = 1.0 //changes v
``````

On the other hand, when performing the following instruction

``````julia> p = v[1:3]
julia> p = 2
2
julia> v
6-element Array{Float64,1}:
1.0
0.0
0.0
0.0
0.0
6.0
``````

I am copying `v` values to a new allocated vector `p`, right?

1 Like

Check out views: https://docs.julialang.org/en/v1.5-dev/base/arrays/#Views-(SubArrays-and-other-view-types)-1. The docs were recently updated to add more description, and I think they are what you’re looking for.

4 Likes

Yes! It seems that this is what I was looking for. Thanks!

However, if anyone has more ideas please let me know!

1 Like

Yeah, a `view` seems like it does exactly what you want:

``````julia> v = [1, 2, 3, 4]
4-element Array{Int64,1}:
1
2
3
4

julia> v_1 = view(v, 1)
0-dimensional view(::Array{Int64,1}, 1) with eltype Int64:
1

julia> v_1[] = 10
10

julia> v
4-element Array{Int64,1}:
10
2
3
4
``````
2 Likes