数组的C指针算术

前端之家收集整理的这篇文章主要介绍了数组的C指针算术前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在阅读K& R中关于阵列算术的部分,并且遇到了一些奇怪的事情.我发布了整段内容,但我主要关注的是大胆的部分.

If p and q point to members of the same array,then relations like ==,@H_403_4@ !=,<,>=,etc.,work properly. For example,p < q is true if p points@H_403_4@ to an earlier member of the array than q does. Any pointer can be@H_403_4@ meaningfully compared for equality or inequality with zero. But the@H_403_4@ behavior is undefined for arithmetic or comparisons with pointers that@H_403_4@ do not point to members of the same array. (There is one exception:@H_403_4@ the address of the first element past the end of an array can be used@H_403_4@ in pointer arithmetic.)

这个例外的原因是什么?在定义大小时,是否将额外的内存分配给任何数组的末尾?如果是这样,为了什么目的?是用空字符结束数组吗?

解决方法

原因是你可以在循环中增加指针,如下所示:
char a[42],*p;

for (p = a; p < &a[sizeof a]; p++)  // or p != &a[sizeof a]
{
   /* ... */
}

如果没有额外的规则,这将是未定义的行为,因为指针将无效.

猜你在找的C&C++相关文章