Reputation: 45
I want to create a copy of an array that already exists, but i want to be able to change values on one of them not altering the other one.
(setf arayONE (make-array(list 2 2)))
(setf arayTWO arayONE)
(setf (aref arayONE 1 1) 2) ; this will change both arayONE and arayTWO values
I also tryed passing the value with the (let ....) statement but gave the same answer..
Thanks sorry for the newbie question.
Upvotes: 0
Views: 83
Reputation: 27404
When you do (setf arayTWO arayONE)
you are actually giving to the same array two different names, since setf
does not perform any copy, but simply assign to the variable arayTWO
the value of arayONE
, which is a reference to an array.
So you have to explicitly copy the array, but since there is no primitive function in Common Lisp to copy arrays, you have to write it by yourself or use the function provided by some library, like Alexandria.
For a simple copy like that of this case, you could for instance write something like this:
(setf arayTWO (make-array (array-dimensions arayONE)))
(dotimes (i (array-total-size arayONE))
(setf (row-major-aref arayTWO i)
(row-major-aref arayONE i)))
For a more general function that works for every kind of array, with fill pointer, adjustability, etc., you could look at this answer: How do you copy an array in common lisp?
Upvotes: 2