简体   繁体   中英

Searching elements in an array

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.

Maybe you want this:

  uint8_t days[5] = { 0x1,0x2,0x3,0x4,0x5 };
  uint16_t search = 0x23;

  for (uint16_t i = 0; i < 4; i++) {             // 4 not 5 because of days[i + 1] below
    uint16_t value = (days[i] << 4) | days[i + 1];

    if (value == search)
    {
      printf("%d", i);
      break;
    }
    else
    {
      printf("not found at %d\n", i);
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM