I want to search the index of the element in array days[] of uint8_t type which has next-to-next elements of 0x2 and 0x3 using a variable of type uint16_t and print the index value of the element '0x2'. I have assigned 'uint16_t search = 0x23' but I am not sure if that will work
#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;
}
To be able to search the uint8 array in pairs as uint16, you need to cast the pointer of the array from uint8 to uint16 before the comparison. Following is how the code should look like:
Note that I am casting the
(uint16_t *)the pointer that was incremented asuint8_twith the(ptr+i)in order to travel trough the array in steps ofuint8_tAlso note that I had lowered the loop to 4 times instead of 5, since by converting the last element of the array to
uint16_tyou will get outside of the boundaries of the array.Finally, the value you are searching should be
0x0302not0x23. First because the0x03and0x02are the values that will be stored in theuint8, and second, since due toendiannessof the CPU, they will be in opposite order in the memory when converted touint16_t