I was browsing a webpage in which there were some answers to frequently asked questions, I found this expression.
Similarly, if a has 10 elements and ip points to [3], you cannot calculate either ip + 10 or ip - 5 access (there is one special case: in this case, you can calculate, but not get access, a pointer to a nonexistent element just outside the array, which in this case is & a [10].
I was embarrassed by the statement
you cannot calculate ip + 10
I understand that accessing an element outside the borders is undefined, but calculation !!!.
I wrote the following snippet that calculates (let me know if this is what the website means by calculation), the pointer is out of bounds.
#include <stdio.h> int main() { int a[10], i; int *p; for (i = 0; i<10; i++) a[i] = i; p = &a[3]; printf("p = %p and p+10 = %p\n", p, p+10); return 0; } $ ./a.out p = 0xbfa53bbc and p+10 = 0xbfa53be4
We see that p + 10 points to 10 elements (40 bytes) per p. So what does the statement made on the web page mean. I misinterpreted something.
Even in K & R (A.7.7) this statement is made:
The result of the + operator is the sum of the operands. A pointer to an object in the array and the value of any integral type .... sum is a pointer of the same type as the original pointer, and points to another object in the same array, the object properly compensates for the original. Thus, if P is a pointer to an object in the array, the expression P + 1 is a pointer to the next object in the array. If the pointer points of the sum are outside the bounds of the array, except for the first place outside the high result, the result is undefined.
Which means "undefined". Does this mean that the amount will be undefined, or will it only mean when we act out its undefined behavior. Is the operation undefined even when we are not looking for it and just compute a pointer to an element outside the bounds.