gpt4 book ai didi

c - 在C中,如何找到数组中元素的偏移量

转载 作者:太空宇宙 更新时间:2023-11-04 06:59:43 24 4
gpt4 key购买 nike

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

我知道我是否需要知道id_arr中ID_C的偏移量,我可以使用像

这样的简单函数
int get_offset(id){
for(i=0;i<id_arr_num;++i){
if(id==id_arr[i]) return i;
}
}

但是 arr 是常量,所以我可以知道 ID_C 的偏移量在运行前将是 2,有什么方法可以使用宏或其他方法在 c 运行时之前知道偏移量吗?

最佳答案

与其直接使用 ID,不如使用本身就是偏移量的索引:

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");

用法很简单:

id = id_arr[IDX_A];

关于c - 在C中,如何找到数组中元素的偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40126046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com