首页 > 解决方案 > 如何测试指针是否在数组中?

问题描述

我想测试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!");
}

编译就好了。

预处理后两者不完全一样吗?

标签: carrayspointerspreprocessorbounds

解决方案


如何测试指针是否在数组中?

代码可以>=, >, <, <=在两个对象指针之间使用p,q是它们在同一个数组中(或者只是一个通过数组的末尾)。否则代码是未定义的行为。C 没有可移植的方式来测试阵列内/外。

下面的代码很差

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");
}

代码可以一次显式地将一个与==, !=withmyCurrentPtr和 的每个元素进行比较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");
}

“如何测试数组中的指针?”的最佳方法 是重新形成问题。OP 没有发布为什么需要这个测试。好的代码通常可以重新处理问题而不使用此测试。


推荐阅读