C K&;将数组简化为指针的R方法
将数组简化为指针的K&R方法:(摘自) K&R试图创建一种统一的数组和指针处理方法,这种方法 将在编译器代码中公开而不是隐藏数组方程。 他们找到了一个优雅的解决方案,尽管有点复杂。“丑陋” 在其公式中,数组方程替换为四条规则:C K&;将数组简化为指针的R方法,c,pointers,multidimensional-array,C,Pointers,Multidimensional Array,将数组简化为指针的K&R方法:(摘自) 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: p
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(这是多维数组的情况)时,除最后一步外,仅取消引用数据类型,而不引用指针值。
#include <stdio.h>
int main() {
int a[] = {42, 1, 5, 89, 7};
int step = 3;
int b = a[step]; // step 1
printf("%d\n", b);
b = *(a + step); // step 2
printf("%d\n", b);
b = *(step + a); // step 3
printf("%d\n", b);
b = step[a]; // step 4
printf("%d\n", b);
return (0);
}
#包括
int main(){
INTA[]={42,1,5,89,7};
int步=3;
int b=a[步骤];//步骤1
printf(“%d\n”,b);
b=*(a+步骤);//步骤2
printf(“%d\n”,b);
b=*(步骤+a);//步骤3
printf(“%d\n”,b);
b=步骤[a];//步骤4
printf(“%d\n”,b);
返回(0);
}
这是可能的,因为:
- 数组被授权为包含相同类型变量/插槽的连续内存块
- 对于
运算符和指针解引用,应用相同的算法,相同的指针算法[]
-
<> LI>这是关键点,指针和数组不是同一个东西,在这种情况下,同样的算法适用于指针和数组,在这种情况下,当你可以将数组看作指针或数组时,使用<代码> []/Cord>运算符,但是指针和数组是2种不同的构造,2种不同的事物。
我添加了一个步骤4,来澄清指针混叠和<代码> []/Cord>运算符之间的相似性。
< P>从您在该问题中提供的链接中,考虑下面的例子:int mat[i][j]
mat[i][j] = *(*(mat + i * sizeof(row)) # j)
- 当递归应用规则#4+规则#3(这是多维数组的情况)时,只有数据类型被取消引用,指针的值不被取消引用,最后一步除外。这意味着
取消对聚合的引用,在我们的例子中,聚合是“一个包含j个元素的整数数组”。只有第二个解引用操作是*(mat+i*sizeof(row))
为您提供实际的*(*(mat+i*sizeof(row))#j
int
- 由于衰减只发生一次,因此上述情况成立。
是指向int数组的指针”*(mat+i*sizeof(row))
x
指向的de>int。它不再是对对象的引用,而是对象。由于引用已不存在,应用*
操作符称为取消引用。@EricPostChil;我知道取消引用:引用指向的数据指针。但取消引用数据类型对我来说是新的。@haccks我同意,取消引用一个数据类型是错误的。改变了它,它现在有意义吗?@ ErpRelistISCHIL让我们不使用这个词引用,因为我们在谈论C,而不是C++,BTW,引用和指针不是一回事。@ EricPostpischil;源已经被引用在问题中(在第一行的末尾)。