这是它的真正工作原理,请参阅代码和注释:
#include <stdio.h>
int x[3][5] =
{
{ 1, 2, 3, 4, 5 },
{ 6, 7, 8, 9, 10 },
{ 11, 12, 13, 14, 15 }
};
int (*pArr35)[3][5] = &x;
// &x is a pointer to an array of 3 arrays of 5 ints.
int (*pArr5a)[5] = x;
// x decays from an array of arrays of 5 ints to
// a pointer to an array of 5 ints,
// x is a pointer to an array of 5 ints.
int (*pArr5b)[5] = &x[0];
// &x[0] is a pointer to 0th element of x,
// x[0] is an array of 5 ints,
// &x[0] is a pointer to an array of 5 ints.
int *pInta = x[0];
// x[0] is 0th element of x,
// x[0] is an array of 5 ints,
// x[0] decays from an array of 5 ints to
// a pointer to an int.
int *pIntb = *x;
// x decays from an array of arrays of 5 ints to
// a pointer to an array of 5 ints,
// x is a pointer to an array of 5 ints,
// *x is an array of 5 ints,
// *x decays from an array of 5 ints to
// a pointer to an int.
int *pIntc = &x[0][0];
// x[0][0] is 0th element of x[0],
// where x[0] is an array of 5 ints,
// x[0][0] is an int,
// &x[0][0] is a pointer to an int.
int main(void)
{
printf("&x=%p x=%p &x[0]=%p x[0]=%p *x=%p &x[0][0]=%p\n",
pArr35, pArr5a, pArr5b, pInta, pIntb, pIntc);
return 0;
}
样本输出:
&x=0040805c x=0040805c &x[0]=0040805c x[0]=0040805c *x=0040805c &x[0][0]=0040805c
所有生成的指针在值方面都是相同的,因为我显式或隐式使用了 0 的索引,并且因为数组是连续的,并且它们的第一个(IOW,第 0 个)元素始终位于数组中的最低地址。因此,即使有 3 种不同的指针类型,它们都有效地指向 x[0][0],指向等于 1 的元素。
数组到指针的衰减是 C 和 C++ 的一个非常重要的特性,尽管很难立即掌握。
它让我们在将指针传递给数组时编写更紧凑的代码,我们可以只写数组的名称而不是获取其第一个元素的地址:
char str1[] = { 's', 't', 'r', '1', '\0' };
char str2[] = "str2";
printf("%s %s %s %s\n", &str1[0], str1, &str2[0], str2);
输出:
str1 str1 str2 str2
它还让我们做一些疯狂的事情:
int y[3] = { 10, 20, 30 };
printf("%d %d %d %d\n", y[2], *(y+2), *(2+y), 2[y]);
输出:
30 30 30 30
这一切a[b]
都等同*(a+b)
于数组和指针。