2

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?

aberdysh
  • 1,634
  • 2
  • 13
  • 34
  • 1
    Possible duplicate of [Creating copies in Julia with = operator](https://stackoverflow.com/questions/33002572/creating-copies-in-julia-with-operator) – Gnimuc Aug 16 '17 at 11:18

1 Answers1

6

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
sbromberger
  • 1,026
  • 6
  • 12
  • 1
    The words _pointer_ and _reference_ aren't quite right and will likely confuse folks who know them from other languages. I'd replace them with _binding_ or _naming_. See JMW's classic blog post: [Values vs. bindings: the map is not the territory](http://www.johnmyleswhite.com/notebook/2014/09/06/values-vs-bindings-the-map-is-not-the-territory/). – mbauman Aug 16 '17 at 16:50
  • Also x-ref to this Metaphor: [A Table of Boxes and Forms and Colorful Stickers](http://blog.leahhanson.us/post/julia/variables.html). – Gnimuc Aug 17 '17 at 00:11