c - 如何测试指针是否在数组中?
问题描述
我想测试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!");
}
编译就好了。
预处理后两者不完全一样吗?
解决方案
如何测试指针是否在数组中?
代码可以>=, >, <, <=
在两个对象指针之间使用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 没有发布为什么需要这个测试。好的代码通常可以重新处理问题而不使用此测试。
推荐阅读
- oracle - 从 ODI 调用 Oracle PL/SQL 存储过程
- javascript - SoundJS 不会从无扩展的 MP3 播放声音
- java - JVM启动时如何预加载使用的类?
- visual-studio - 如何在 VS2019 中将 -0x80000000 分配给 long long 变量?
- .net-core - net core 3.1 runtime backword 与 2.2 的兼容性
- amazon-web-services - VPC 之外的 lambda 可以使用 rds 代理访问 aurora rds 吗?
- macos - glfw 拖动窗口最初在 macOS 上是滞后的
- javascript - javascript document.getelementbyid() 不适用于 html 加载循环
- javascript - Bootstrap:无法使页面响应所有屏幕
- r - 获取数据框 R 的所有列的平均值