2

我正在研究一种简单的 lisp 风格的预处理器语言。在 API 中,我希望用户能够将任何维度和大小的数组传递给可以使用该语言进行操作的预处理器。目前我有一个类型的枚举;

typedef enum LISP_TYPE
{
  LT_UINT,
  LT_FLOAT,
  LT_ARRAY
  ...,
  ...
} _LISP_TYPE;

我很难找到一种有效且易于使用的方法来存储数组并访问它们。我专门用于数组的另一种结构;

typedef struct _lisp_array
{
  LISP_TYPE type;
  unsigned int length;
  void* data;

} lisp_array;

当预处理器 See 是一个类型为 LT_ARRAY 的列表原子时,它会将其void*(在 lisp 术语中的 cdr)转换为上述结构。我遇到问题的地方是弄清楚如何访问多维数组。我曾想过计算一个步长值来遍历数组,但我能保证所有传递的数组都将被连续分配吗?

任何帮助表示赞赏。

4

3 回答 3

0

C built-in (singe and multi-dimensional) arrays are guaranteed to be stored in one contiguous region of memory in row-major mode. This may not answer your question, however. What is the expected layout of the data structure pointed to by _lisp_array::data member?

于 2011-01-24T17:25:32.997 回答
0

Since you're writing the interpreter, it's up to you to decide on the representation and make the array contiguous - that is, if you need it to be contiguous. If you make it contiguous, you can access elements by, for example (assuming zero-based indices a, b, c... and dimension size sa, sb, sc...):

(a*sb + b) * sc + c   ... (row major order)
(c * sb + b) * sa + a ... (column major order)

There are other ways of representing arrays, of course - you could use arrays-of-pointers-to-arrays, etc. Each has its own advantages and disadvantages; without any specifics on the use case, if the bounds of the array are fixed, and the array is not expected to be sparse, then a contiguous buffer is usually a reasonable approach.

于 2011-01-24T17:32:56.070 回答
0

这将取决于你想要让它变得像 lisp 那样,真的。Lisp 没有你所想的多维数组的严格定义——一切要么是原子,要么是列表。它最接近的东西是数组数组:

((1 2 3) (4) (5 6))

但请注意,子数组的长度不同。但它们不一定是天生的,而且我认为没有办法强迫这个问题......

如果你需要严格的“矩形”数组,这显然是行不通的,但如果你有回旋余地,这就是我的实现方式——这是一个很好、干净的结构(查看维基百科页面了解更多详细信息)。

干杯!

于 2011-01-26T02:46:23.913 回答