我正在阅读K& R中关于阵列算术的部分,并且遇到了一些奇怪的事情.我发布了整段内容,但我主要关注的是大胆的部分.
If p and q point to members of the same array,then relations like ==,
!=,<,>=,etc.,work properly. For example,p < q is true if p points
to an earlier member of the array than q does. Any pointer can be
meaningfully compared for equality or inequality with zero. But the
behavior is undefined for arithmetic or comparisons with pointers that
do not point to members of the same array. (There is one exception:
the address of the first element past the end of an array can be used
in pointer arithmetic.)
这个例外的原因是什么?在定义大小时,是否将额外的内存分配给任何数组的末尾?如果是这样,为了什么目的?是用空字符结束数组吗?
解决方法
原因是你可以在循环中增加指针,如下所示:
char a[42],*p; for (p = a; p < &a[sizeof a]; p++) // or p != &a[sizeof a] { /* ... */ }
如果没有额外的规则,这将是未定义的行为,因为指针将无效.