为什么在C中展开多维数组是非法的?

前端之家收集整理的这篇文章主要介绍了为什么在C中展开多维数组是非法的?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > One-dimensional access to a multidimensional array: well-defined C?4个
我的书(Kenneth Reek的C指针)说,以下是非法的,尽管它工作正常.
int arr[5][5];
  int *p=&arr[2][2];
  p=p+3; // As array is stored in row major form I think this 
         //should make p point to arr[3][0]

这本书说,下一行留下一行是非法的.但我不明白为什么.

解决方法

我凝视了一段时间,我会尽力解释我认为他来自哪里,虽然没有阅读这本书,但这将是最好的推测.

首先,在技术上,你提出的增量(或他提出)并不是非法的;取消引用它是.该标准允许您将一个指针提前一个,超过数组序列的最后一个元素,从它的采购来估值,而不是取消引用.将其更改为p = p 4,并且都是非法的.

除此之外,阵列的线性足迹不能承受,ar [2]有一种类型,它是int [5].如果您不信,请考虑以下内容,所有这些都正确键入:

int ar[5][5];
int (*sub)[5] = ar+2;   // sub points to 3rd row
int *col = *sub + 2;    // col points to 3rd column of third row.
int *p = col + 3;       // p points to 5th colum of third row.

这是否属于ar [3] [0]是不相关的您超过了指定数学的维度的声明幅度.结果不能在法律上被解除引用,并且比3偏移大,也不能甚至被法定评估.

记住,正在寻址的阵列是ar [2];不仅仅是ar,而是说相同的被宣称为size = 5.它与同一个ilk的另外两个数组相反,与目前正在进行的寻址无关.我相信Christoph’s answer提出的这个问题,应该是一个被选为彻底解决方案的人.特别是参考C99§6.5.6,p8,尽管如此,

@H_403_21@

When an expression that has integer type is added to or subtracted
from a pointer,the result has the type of the pointer operand. If the
pointer operand points to an element of an array object,and the array
is large enough,the result points to an element offset from the
original element such that the difference of the subscripts of the
resulting and original array elements equals the integer expression.
In other words,if the expression P points to the i-th element of an
array object,the expressions (P)+N (equivalently,N+(P)) and (P)-N
(where N has the value n) point to,respectively,the i+n-th and
i−n-th elements of the array object,provided they exist. Moreover,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.

对不起垃圾邮件,但大胆的亮点是我认为与您的问题相关的.通过解决您的问题,您正在离开正在被处理的阵列,并且这样走进UB.总之,它的作品(通常),但是是不合法的.

原文链接:https://www.f2er.com/c/113596.html

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