我可能误解了这一点,但是c99规范是否阻止了对动态分配内存的任何形式的指针算法?
从6.5.6p7起……
For the purposes of these operators,a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.
…指向不在数组中的对象的指针被视为指向1项的数组(当使用运算符和 – 时).然后在这个片段中:
char *make_array (void) {
char *p = malloc(2*sizeof(*p));
p[0] = 1; // valid
p[1] = 2; // invalid ?
return p;
}
……第二个下标p [1]无效?由于p指向不在数组中的对象,因此它被视为指向一个项目的数组中的对象,然后从6.5.6p8 …
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.
…我们有未定义的行为,因为我们取消引用数组绑定(隐含长度为1的那个).
编辑:
好的,为了澄清更让我困惑的事情,让我们一步一步地做:
1.)p [1]定义为*(p 1).
2.)p指向不在数组内部的对象,因此它被视为指向长度为1的数组内的对象,以便评估p 1.
3.)p 1产生一个指针1超过p隐含指向的数组.
4.)*(p 1)执行无效解除引用.
从C99,7.20.3开始 – 内存管理功能(强调我的):
The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object or an array of such objects in the space allocated (until the space is explicitly deallocated).
这意味着分配的内存可以作为char数组访问(根据您的示例),因此指针算法定义良好.