let int * ptr,array[10]; ptr=数组;
。现在阵列的连续位置中的每个存储单元都有固定的大小。如果第一个单元格的地址是 1234,那么下一个单元格的地址必须是 1238。但是我们使用指针作为 *(ptr+1)
来访问它。
我对此感到困惑。任何来源或答案?谢谢。
最佳答案
来自 C11 standard: §6.5.2.1
A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).
例如你正在做的基本上就是 []
已经做的
还(相同标准)解释了为什么指针会像您注意到的那样递增:§6.5.6
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.
关于c++ - 通过指针访问数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18020332/