简体   繁体   中英

Does pointer arithmetic still work outside the array?

I am always reading that pointer arithmetic is defined as long as you don't leave the bounds of the array. I am not sure I completely understand what this means and I was a little worried. Hence this question.

Suppose I start with a pointer to the beginning of an array:

int *p = (int*) malloc(4 * sizeof(int));

Now I create two new pointers that lie outside the bounds of the array:

int *q = p + 10;
int *r = p - 2;

Now the pointers q-10 , q-9 , ..., r+2 , r+3 , and so on all lie inside the bounds of the array. Are they valid? For example, is r[3] guaranteed to give the same result as p[1] ?

I have done some testing and it works. But I want to know if this is covered by the usual C specifications. Specifically, I am using Visual Studio 2010, Windows, and I am programming in native C (not C++). Am I covered?

What you're doing works on the implementation you're using, as well as most popular implementations, but it's not conforming C. As chris cited,

§6.5.6/8: 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

The fact that it's undefined will probably become increasingly important in the future, with more advanced static analysis allowing compilers to turn this kind of code into fatal errors without incurring runtime cost.

By the way, the historical reason for subtracting pointers not within the same array being undefined is segmented memory (think 16-bit x86; those familiar with it will want to think of the "large" memory model). While pointers might involve a segment and offset component, a compiler could do the arithmetic just on the offset component to avoid runtime cost. This makes arithmetic between pointers not in the same segment invalid since the "high part" of the difference is lost.

According to the C11 standard, §6.5.6/8 (I put in the first part for context):

When an expression that has integer type is added to or subtracted from a pointer
...
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.

Therefore, a result that is outside of the array and not one past the end is undefined behaviour.

"Yes" the conditions you mentioned are covered in specifications.

int *r = p - 2;

r is outside bounds of array p, the evaluation results in allocation of position to r, 2 int positions behind/before the address of p.

`r[3]` is simply the "4th" int position after the address of r

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM