指针比较"<"一个过去的数组对象的最后一个元素 [英] pointer comparisons "<" with one past the last element of an array object

查看:88
本文介绍了指针比较"<"一个过去的数组对象的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道用指针比较< 允许使用C standrad只有当指针指向相同的内存空间(如数组)

如果我们把一个数组:

  int数组[10];
为int * PTR =安培;数组[0];

在比较 PTR 阵列+ 10 允许吗?是阵列+ 10 数组的内存,因此对比是不允许的?

之外的考虑指针

例如

 为(PTR =安培;数组[0]; PTR≤(阵列+ 10); PTR ++){...}


解决方案

是的,指针允许指向的位置刚刚过去的数组的末尾。然而,你不允许这种尊重的指针。


  

C99 6.5.6 / 8加法运算符(强调)


  
  

如果EX pression p指向数组对象的最后一个元素时,
  前pression(P)+1点中的一个过去的数组对象的最后一个元素,
  如果前pression Q点中的一个过去的数组的最后一个元素
  对象,前pression(Q)-1点到所述阵列的最后一个元素
  目的。如果指针操作数和结果指向元素都
  相同的数组对象,或者一个过去的数组的最后一个元素
  对象
后,该评估也不得产生溢出;否则,
  行为是不确定的。如果结果点中的一个过去的最后一个元素
  数组对象的,不得被用来作为一元的操作数​​
  操作员进行了评估。


和,专门为指针比较操作:


  

C99 6.5.8 / 10关系运算符


  
  

如果除权pression p指向数组对象的元素和
  前pression Q指向相同的数组对象的最后一个元素时,
  指针前pression Q + 1大于P.更大的比较在其它情况下,
  该行为是不确定的。


I know the pointer comparisons with < is allowed in C standrad only when the pointers point at the same memory space (like array).

if we take an array:

int array[10];
int *ptr = &array[0];

is comparing ptr to array+10 allowed? Is the array+10 pointer considered outside the array memory and so the comparison is not allowed?

example

for(ptr=&array[0]; ptr<(array+10); ptr++) {...}

解决方案

Yes, a pointer is permitted to point to the location just past the end of the array. However you aren't permitted to deference such a pointer.

C99 6.5.6/8 Additive operators (emphasis added)

if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object. If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. If the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.

And, specifically for comparision operations on pointers:

C99 6.5.8/5 Relational operators

If the expression P points to an element of an array object and the expression Q points to the last element of the same array object, the pointer expression Q+1 compares greater than P. In all other cases, the behavior is undefined.

这篇关于指针比较&QUOT;&LT;&QUOT;一个过去的数组对象的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆