#include <stdio.h>
int main(void)
{
int a[5] = { 1, 2, 3, 4, 5 };
int *ptr = (int*)(&a + 1); // what happens here ?
printf("%d %d\n", *(a + 1), *(ptr - 1));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我预计答案是1但是得到5 ..为什么?
Dan*_*her 11
int *ptr = (int*)(&a + 1); // what happen here ?
Run Code Online (Sandbox Code Playgroud)
获取数组的地址,然后向其添加1,这将产生指向sizeof a字节超过开头的字节的指针a.然后int*将该指针强制转换为a ,并将其指定给ptr.同样可以实现
int *ptr = &a[5];
Run Code Online (Sandbox Code Playgroud)
在这种情况下.
然后ptr - 1是指向指针sizeof(int)之前字节ptr,也就是要&a[4]和*(ptr - 1)是a[4].
指针算术以"指针大小"为单位完成.因为&a是一个指向5 int- a数组的指针int (*)[5],所以向它添加1会移动它的5*sizeof(int)字节.
&a是指向指针的指针int[5],因此&a + 1也是指针int[5].松散&,所有都应该没问题(而且你也不再需要演员):
int *ptr = a + 1;
Run Code Online (Sandbox Code Playgroud)