I have two arrays A and B. Let's say A=[1,2,3] and B=[4,5,6]. I want to define a third array C = append!(A,B). The problem is this also changes A to be A=[1,2,3,4,5,6]. How to avoid this problem?
CodePudding user response:
append! pushes the elements of the second collection to the first one, modifying it, to just concatenate them, use vcat:
C = vcat(A, B)
Or you can use ; to build a new array from the contents of A and B:
C = [A ; B]
CodePudding user response:
You could try this:
A=[1,2,3]
B=[4,5,6]
C=A
append!(C,B)
Then C = [1,2,3,4,5,6] and B = [4,5,6]. But unfortunately, A = [1,2,3,4,5,6].
The problem is C=A, which makes A and C the same in every way, except for the variable name. Unfortunately, changes to C then also change A, because they occupy the same area of memory, they have the same address.
What you have to do is to copy A to C, before appending B. Then C and A have the same data, before B is appended, but they are separate things. Changing C no longer changes A.
A = [1,2,3]
B = [4,5,6]
C=copy(A)
append!(C,B)
Then C = [1,2,3,4,5,6] and B = [4,5,6]. And, A = [1,2,3].
