【发布时间】:2021-06-03 02:10:30
【问题描述】:
我想使用 uint16_t 类型的变量搜索 uint8_t 类型的数组 days[] 中的元素的索引,该元素的下一个元素为 0x2 和 0x3,并打印元素“0x2”的索引值。我已经分配了 'uint16_t search = 0x23' 但我不确定这是否可行
#include <stdio.h>
#include <stdint.h>
int main()
{
uint8_t days[5] = {0x1,0x2,0x3,0x4,0x5};
uint8_t *ptr = days;
uint16_t search = 0x23;
for(uint16_t i=0;i<5;i++){
if (*(ptr+i) == search){
printf("%d", i);
break;
}else{
printf("not found at %d\n", i);
}
}
return 0;
}
【问题讨论】:
-
是否要将数组的两个连续 uint8 元素读取为 uint16?如果是,你必须小心不要触发UB。此外,正确性取决于字节序
-
是的,我想将两个连续的 uint8_t 元素读取为 uint16_t。
-
OT:
ptr没用,只需替换为*(days+i)或者更好的是days[i]这是惯用的方式。 -
请确定:您希望
search = 0x34的输出是什么? -
您确定要搜索
0x23而不是0x0203?days是否可以包含大于0x9的值?