aberdysh
aberdysh

Reputation: 1664

Julia: array assignment behaviour

My question is about the change of array elements. Consider the following code snippet:

julia> a = [1 2; 3 4]
2×2 Array{Int64,2}:
 1  2
 3  4

julia> b = a
2×2 Array{Int64,2}:
 1  2
 3  4

julia> a[1,1] = -1
-1

julia> b
2×2 Array{Int64,2}:
 -1  2
  3  4

However, when I run the following instead:

julia> a = [1 2; 3 4]
2×2 Array{Int64,2}:
 1  2
 3  4

julia> b = a
2×2 Array{Int64,2}:
 1  2
 3  4

julia> a = [5 6; 7 8]
2×2 Array{Int64,2}:
 5  6
 7  8

julia> b
2×2 Array{Int64,2}:
 1  2
 3  4

Array b remains unchanged? Why is that, can anyone explain this?

Upvotes: 2

Views: 418

Answers (1)

sbromberger
sbromberger

Reputation: 1026

In the first example, you are creating an array and assigning a pointer to that array to a. You then assign the same pointer to b in line 2, so that a and b are references to the same memory location. When you mutate an element in the array, you do not change where a and b are pointing, so that both a and b both reflect the new value in the first memory offset within the array.

In the second example, you create an array and assign a pointer to a. You then assign the same pointer to b, just as before, but you next create a new array in a different memory location and assign that location to a. a and b are now pointing to two different memory locations, each with their own arrays.

Here's a demonstration:

julia> a = [1 2; 3 4]
2×2 Array{Int64,2}:
 1  2
 3  4

julia> pointer(a)   # show the memory location of the array
Ptr{Int64} @0x000000011cd1a120

julia> b = a
2×2 Array{Int64,2}:
 1  2
 3  4

julia> pointer(b)   # note - same memory location
Ptr{Int64} @0x000000011cd1a120

julia> a = [5 6; 7 8]
2×2 Array{Int64,2}:
 5  6
 7  8

julia> pointer(a)    # note - new array; new memory location
Ptr{Int64} @0x000000011d259e80

julia> pointer(b)    # still referencing the first array's location.
Ptr{Int64} @0x000000011cd1a120

Upvotes: 6

Related Questions