I would like to test if myCurrentPtr
points inside my array a
.
_B
represents the number of values in a
.
So, a + _B
shall point the latest value of the array.
#define _B ((uint8_t)5)
volatile uint8_t a[5] = {0, 1, 2, 3, 4}; //`a` is a pointer to the first array element
if (myCurrentPtr > (a + _B)) {
printf("Out of bounds!");
}
Doesn't compile. Do you have any idea?
Whereas,
...
if (myCurrentPtr > (a + 5)) {
printf("Out of bounds!");
}
compiles just fine.
Aren't the two exactly the same after preprocessing?
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.