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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…