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:
#include <stdio.h>
#include <stdint.h>
int main()
{
uint8_t days[5] = {0x1,0x2,0x3,0x4,0x5};
uint8_t *ptr = days;
uint16_t search = 0x0302;
for(uint16_t i=0;i<4;i++){
if (*((uint16_t *) (ptr+i) ) == search){
printf("%d", i);
break;
}else{
printf("not found at %d\n", i);
}
}
return 0;
}
Note that I am casting the (uint16_t *)
the pointer that was incremented as uint8_t
with the (ptr+i)
in order to travel trough the array in steps of uint8_t
Also note that I had lowered the loop to 4 times instead of 5, since by converting the last element of the array to uint16_t
you will get outside of the boundaries of the array.
Finally, the value you are searching should be 0x0302
not 0x23
. First because the 0x03
and 0x02
are the values that will be stored in the uint8
, and second, since due to endianness
of the CPU, they will be in opposite order in the memory when converted to uint16_t
Note: When using cast you should be certain how the cast will be interpreted, meaning not to overrun the boundaries of the variables, otherwise you might cause segmentation faults, or even silent problems which will lead to an undefined behavior of your program.