我偶然发现了“指向整个数组的指针” ,并编写了一个测试程序来清除一些东西:
#include <stdio.h>
int main(){
int x[5] = {1, 2, 3, 4, 5};
int *a = x; // points to the 1st array element
int (*b)[5] = &x; // points to the 1st addres of the stream of 5 int elements
int (*c)[5] = x; // points to the 1st addres of the stream of 5 int elements
printf("%p\n%p\n%p\n\n",
(void *)a,
(void *)b,
(void *)c
);
++a;
++b;
++c;
printf("%p\n%p\n%p\n\n",
(void *)a,
(void *)b,
(void *)c
);
return 0;
}
这将输出:
0x7ffed0c20690
0x7ffed0c20690
0x7ffed0c20690
0x7ffed0c20694
0x7ffed0c206a4
0x7ffed0c206a4
对我来说,它看起来像是线条:
int (*b)[5] = &x;
int (*c)[5] = x;
获得完全相同的结果,因为:
他们分配相同的地址(在*b
的情况下,它是整个数组的地址;在*c
的情况下,它是第一个数组成员的地址,但那些两个重叠)和
为int
和*b
分配相同的指针大小5·*c
,这在我增加值时得出完全相同的指针算法。
问题1:我所缺少的*b
和*c
的定义之间是否存在任何隐藏的区别?
第二季度:指针算术仅取决于指针的大小吗?
在您指出之后,我注意到我确实收到了一个错误:
main.c:9:16: warning: initialization of ‘int (*)[5]’ from incompatible pointer type ‘int *’ [-Wincompatible-pointer-types]
int (*c)[5] = x; // points to the 1st array element
答案 0 :(得分:3)
问题1:
*b
和*c
的定义之间存在任何隐藏的区别 失踪了吗?
这两个指针的指针算法将保持不变。因为内部数组会衰减为指向其中第一个元素的指针,即arr[n]
将被转换为类型为“ pointer to arr
”的表达式,其值将为数组中第一个元素的地址。
Q2:指针算术仅取决于指针的大小吗?
否,这取决于所指向的基础类型的大小。即使在您提供的样本输入中,++a
和++b
也会产生不同的结果。因为++a
使指针偏移了sizeof(int)
(即4),但是在++b
的情况下,您的指针会以5 * sizeof(int)
的大小增加20(十进制)