How to test if pointer inside an array?
Code can use >=, >, <, <= between two object pointers p,q is they are in the same array (or just one passed the end of the array). Else code is undefined behavior. C does not have a portable way to test in/outside the array.
The below code is poor
if (myCurrentPtr == (a + _B)) { // Defined behavior
printf("pointer just passed a[]\n");
} else if (myCurrentPtr >= a && myCurrentPtr < (a + _B)) { // Undefined behavior
printf("pointer in array\n");
} else {
printf("pointer outside array\n");
}
Code could explicitly compare one at a time with ==, != with myCurrentPtr and each element of a[]. Likely this is unsatisfactorily slow, yet reliable.
// Dependable, well defined, but slow.
found = false;
for (int i=0; i<5; i++) {
if (myCurrentPtr == &a[i]) {
found = true;
break;
}
}
Other approaches rely on iffy code.
// Iffy code - depending on memory model, may work, may not.
uintptr_t mcp = (uintptr_t) myCurrentPtr;
uintptr_t ia = (uintptr_t) a;
uintptr_t ia5 = (uintptr_t) &a[5];
if (mcp >= ia && mcp < ia5) { // Not highly portable
printf("pointer in array\n");
} else {
printf("pointer just passed a[]\n");
}
The best approach to "How to test if pointer inside an array?" is to re-form the problem. OP did not post why this test is needed. Good code typically can re-work the issue and not use this test.
(a + 5)use(a + sizeof(a)*sizeof (<type_of_a>)).a + _Bpoints one pass the last.