C和指针 第八章 数组 问题一
定义 int a[20];
int *ip = a + 3;
假定a数组在内存的起始位置是100.请问表达式a, &a,&a[4],&a+4和ip,&ip,&ip[4],&ip+4的值为多少?
很容易知道,a = 100; &a = 100; &a[4] = 116 . ip = 112; &ip值未知(假定某次为8000); &ip[4] = 128 .
那么,&a+4和&ip+4,到底为多少?
书上的答案,说&a+4 = 116. 我对此很疑惑,于是用VC,DEV-C++和GCC跑了一下,发现答案不是116.而应该是420.
而&ip + 4 = 8016.
分析原因,我猜测&a+4 =420的理由是: &a = 100,+4最终加的是:4* sizeof(a[20]) = 4 * 80 = 320。
而ip的定义就是指向整型的指针,所以&ip+4中的+4为: 4* sizeof(int*) = 16.
不知道其他编译器的结果如何。
之后我在stackoverflow上问了这个问题,给出一个我觉得不错的答案:
&a
is a pointer to an array of int with 20 elements (the type is int (*)[20]
).
So &a + 4
is different than a + 4
since in the second expression a
evaluates to a pointer to the first element (it evaluates to a pointer of type int*
). The pointer arithmetic works out differently since the pointer types are different, even though the value of &a
and a
are the same.