将数组简化为指针的 K&R 方法:(摘自C 中的数组和指针)
K&R 试图创建一个数组和指针的统一处理,一种在编译器代码中公开而不是隐藏数组方程的处理。他们找到了一个优雅的解决方案,尽管有点复杂。“丑陋”的数组方程在其公式中被四个规则所取代:
1) An array of dimension N is a 1D array with
elements that are arrays of dimension N-1.
2) Pointer addition is defined by:
ptr # n = ptr + n * size(type-pointed-into)
"#" denotes here pointer addition to avoid
confusion with ordinary addition.
The function "size()" returns object's sizes.
3) The famous "decay convention": an array is
treated as a pointer that points to the
first element of the array.
The decay convention shouldn't be applied
more than once to the same object.
4) Taking a subscript with value i is equivalent
to the operation: "pointer-add i and then
type-dereference the sum", i.e.
xxx[i] = *(xxx # i)
When rule #4 + rule #3 are applied recursively
(this is the case of a multi-dimensional array),
only the data type is dereferenced and not the
pointer's value, except on the last step.
我不明白这是什么意思
- 衰减约定不应多次应用于同一对象(在规则 #3 中)。
- 当递归应用规则#4 + 规则#3 时(这是多维数组的情况),只有数据类型被取消引用,而不是指针的值,除了最后一步。
有人可以用例子来解释吗?