如何测试数组中的指针?

问题描述 投票:-1回答:1

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

不编译。你有什么主意吗?

Whereas,

...
if (myCurrentPtr > (a + 5)) {
    printf("Out of bounds!");
}

编译就可以了。

预处理后两个不是完全相同吗?

c arrays pointers preprocessor bounds
1个回答
0
投票

我不知道您的编译错误在哪里,但这在我的系统上有效(使用gcc和clang编译):

#include <stdio.h>
#include <stdint.h>

#define _B ((uint8_t)5)

int main(){
   volatile uint8_t a[5] = {0, 1, 2, 3, 4}; //`a` is a pointer to the first array element
   volatile uint8_t *myCurrentPtr = &a[2];

   if (myCurrentPtr > (a + _B)) {
    printf("Out of bounds!");
   }
   else
   {
    printf("In array!");
   }
}

输出:

In array!
© www.soinside.com 2019 - 2024. All rights reserved.