这行如何添加带有常量的数组?

How can this line add array with constants?

我正在查看 line 272 of the 8086tiny 的源代码。有

// regs16 and reg8 point to F000:0, the start of memory-mapped registers. CS is initialised to F000
regs16 = (unsigned short *)(regs8 = mem + REGS_BASE);

REGS_BASE

#define RAM_SIZE 0x10FFF0
#define REGS_BASE 0xF0000

Line 158 & 159memregs8regs16 定义为

unsigned char mem[RAM_SIZE],*regs8;
unsigned short *regs16;

所以我的问题是:行 regs8 = mem + REGS_BASE 的作用是什么?如何添加一个带有常量(REGS_BASE)的数组(mem)?感谢您的帮助!

数组名代表第一个元素地址

unsigned char mem[RAM_SIZE];

mem 等于 &mem[0]

决定:(n 是常量) mem[n] = *(mem + n)

mem + n 是一个地址,您可以将其分配给适当的指针。

How can this line add array with constants?

C 标准说(从 ISO/IEC 9899:201x 委员会草案复制 — 2011 年 4 月 12 日 N1570):

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object ...

所以当使用数组时,即 mem,在 mem + ... 形式的表达式中,mem 被转换为 指向第一个元素的指针数组.

对于添加,标准说:

When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i+n-th and i−n-th elements of the array object, provided they exist.

因此,将一个整数 N 加到一个指向数组元素的指针上,就会得到一个指向原始指针指向的元素之后 N 个位置的元素的指针。

在您的情况下,这意味着:

Pointer to first element (aka pointer to mem[0])
 |
 |       Integer
 |        |
/-\   /-------\

mem + REGS_BASE

\-------------/
       |
      Pointer to the REGS_BASE'th element (aka pointer to mem[REGS_BASE])

在您的代码中,此指针被分配给 reg8 并且 - 在转换之后 - 被分配给 reg16.