# 定义二维数组的陷阱

`(make-vector 2 (make-vector 3 0))` 定义一个二行三列数组似乎符合直觉，但有陷阱，同样是修改 `[0, 0]`，对比：

``````(let ((vec (make-vector 2 (make-vector 3 0))))
(setf (elt (elt vec 0) 0) 100)
vec)
;; => [[100 0 0] [100 0 0]]

(let ((vec [[0 0 0]
[0 0 0]]))
(setf (elt (elt vec 0) 0) 100)
vec)
;; => [[100 0 0] [0 0 0]]
``````

``````(defun my-make-two-dims-array (width height)
(let ((vec (make-vector height nil)))
(dotimes (i height vec)
(setf (elt vec i) (make-vector width 0)))))

(let ((vec (my-make-two-dims-array 3 2)))
(setf (elt (elt vec 0) 0) 100)
vec)
;; => [[100 0 0] [0 0 0]]``````
2 个赞

```DEFUN ("make-vector", Fmake_vector, Smake_vector, 2, 2, 0,
doc: /* Return a newly created vector of length LENGTH, with each element being INIT.
(Lisp_Object length, Lisp_Object init)
{
CHECK_NATNUM (length);
struct Lisp_Vector *p = allocate_vector (XFASTINT (length));
for (ptrdiff_t i = 0; i < XFASTINT (length); i++)
p->contents[i] = init;
return make_lisp_ptr (p, Lisp_Vectorlike);
}
```

1 个赞

``````(defun my-make-two-dims-array (width height)
(apply 'vector
(mapcar '(lambda (A)(make-vector width 0))
(make-string height ?A))))
``````

Emacs Lisp里除了基本类型以外都是传递指针的吧？

Emacs Lisp 有不少和 Mutable 相关的陷阱。

2 个赞

1 个赞

1 个赞