如何测试指针是否在数组内?
How to test if pointer inside an array?
我想测试 myCurrentPtr
是否指向我的数组 a
。
_B
表示a
.
中值的个数
所以,a + _B
应该指向数组的最新值。
#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!");
}
不编译。你有什么想法吗?
然而,
...
if (myCurrentPtr > (a + 5)) {
printf("Out of bounds!");
}
编译得很好。
两者经过预处理是不是一模一样?
How to test if pointer inside an array?
代码可以在两个对象指针之间使用 >=, >, <, <=
p,q
是它们在同一个数组中(或者只是一个通过了数组的末尾)。其他代码是 未定义的行为 。 C 没有可移植的方法来测试 in/outside 数组。
下面的代码很差
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");
}
代码可以明确地一次比较一个 ==, !=
和 myCurrentPtr
以及 a[]
的每个元素。这可能慢得令人不满意,但可靠。
// Dependable, well defined, but slow.
found = false;
for (int i=0; i<5; i++) {
if (myCurrentPtr == &a[i]) {
found = true;
break;
}
}
其他方法依赖于不确定的代码。
// 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");
}
最好的方法到"How to test if pointer inside an array?"是重新形成问题。 OP 没有post 为什么 需要这个测试。好的代码通常可以重新解决问题而不使用此测试。
我想测试 myCurrentPtr
是否指向我的数组 a
。
_B
表示a
.
中值的个数
所以,a + _B
应该指向数组的最新值。
#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!");
}
不编译。你有什么想法吗?
然而,
...
if (myCurrentPtr > (a + 5)) {
printf("Out of bounds!");
}
编译得很好。
两者经过预处理是不是一模一样?
How to test if pointer inside an array?
代码可以在两个对象指针之间使用 >=, >, <, <=
p,q
是它们在同一个数组中(或者只是一个通过了数组的末尾)。其他代码是 未定义的行为 。 C 没有可移植的方法来测试 in/outside 数组。
下面的代码很差
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");
}
代码可以明确地一次比较一个 ==, !=
和 myCurrentPtr
以及 a[]
的每个元素。这可能慢得令人不满意,但可靠。
// Dependable, well defined, but slow.
found = false;
for (int i=0; i<5; i++) {
if (myCurrentPtr == &a[i]) {
found = true;
break;
}
}
其他方法依赖于不确定的代码。
// 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");
}
最好的方法到"How to test if pointer inside an array?"是重新形成问题。 OP 没有post 为什么 需要这个测试。好的代码通常可以重新解决问题而不使用此测试。