指针可以指向数组size 的下一个, 即just beyond it by one element(non-existent)

来源:互联网 发布:java静态代理模式 编辑:程序博客网 时间:2024/06/06 09:33

是的。 that is true, 这是一个special case。 

举个例子, 我们声明一个arr[10], 即有10个数组元素的数组。 如果我们当然不能够access到arr[-1], 或者arr[50]甚至arr[10]等等。 同样, 如果有一个指针*p指向这个数组arr, 显然 p + 11, p -2是违法的。 但是有一个special case, 就是p + 10 是合法的, 很奇怪? 当时就是这样。 p + 10 后指向的是第11个元素, 即数组的第10个元素的下一个位置, 然而我们知道数组总共size就是10, 所以p + 10 是指向一个nonexistent的element, just (必须)beyond the end of the array, which is &arr[10](数组的下标是从0开始记的)。然而这是合法的, 前提是只要你不access(即read 和write)这个位置, 这也说明了我们可以通过-1的操作时期指向数组的最后的一个元素了。 这一规定是very useful的。 下面说明用处。

As we've seen, you can add an integer to a pointer to get a new pointer, pointing somewhere beyond the original (as long as it's in the same array). For example, you might write

ip2 = ip1 + 3;
Applying a little algebra, you might wonder whether
ip2 - ip1 = 3
and the answer is, yes. When you subtract two pointers, as long as they point into the same array, the result is the number of elements separating them. You can also ask (again, as long as they point into the same array) whether one pointer is greater or less than another: one pointer is ``greater than'' another if it points beyond where the other one points. You can also compare pointers for equality and inequality: two pointers are equal if they point to the same variable or to the same cell in an array, and are (obviously) unequal if they don't. (When testing for equality or inequality, the two pointers do not have to point into the same array.)

One common use of pointer comparisons is when copying arrays using pointers. Here is a code fragment which copies 10 elements from array1 to array2, using pointers. It uses an end pointer, ep, to keep track of when it should stop copying.

int array1[10], array2[10];int *ip1, *ip2 = &array2[0];int *ep = &array1[10];for(ip1 = &array1[0]; ip1 < ep; ip1++)*ip2++ = *ip1;
As we mentioned, there is no element array1[10], but it is legal to compute a pointer to this (nonexistent) element, as long as we only use it in pointer comparisons like this (that is, as long as we never try to fetch or store the value that it points to.)

0 0