简体   繁体   中英

In C, how to find an offset of element in array

#define ID_A 5
#define ID_B 7
#define ID_C 9
const int id_arr={ ID_A, ID_B, ID_C, };

I know if I need to know the offset of ID_C in id_arr, I can use a simple function like

int get_offset(id){
   for(i=0;i<id_arr_num;++i){
       if(id==id_arr[i]) return i;
   }
}

But arr is const, so I can know offset of ID_C will be 2 before runtime, is any way to use macro or other way to know the offset before c runtime?

Rather than using ID's directly, use indexes that themselves are offsets:

enum {
    IDX_A,
    IDX_B,
    IDX_C,
    IDX_COUNT
};
const int id_arr={ 5, 7, 9 };
/* Error checking to make sure enum and array have same number of elements (from assert.h) */
static_assert((sizeof id_arr / sizeof *id_arr) == IDX_COUNT, "Enum/array mismatch");

Usage is simple:

id = id_arr[IDX_A];

Avoid using macros for that.
And you forgot to define id_arr_num .
No, there is no way of knowing this index before runtime, and avoid using global values as much as possible.

This function will give you the index of the variable you're looking for:

int get_offset(id, arr, size){
   for(i = 0;i < size;++i)
       if(id == arr[i]) return 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