我正在尝试在C(C99)编译时生成一个大的常量查找表,并且该查找表的每个条目都有一个指向另一个const数组的指针。我希望能够一次构建所有这些数组,但这是不可能的,因为大括号初始化程序不能用于指针。是否可以使用一些预处理器宏或其他技巧来定义“匿名”数组或类似的东西,以便可以将它们包括在嵌套数据结构中?
我在下面创建了一个示例,显示了我当前正在做的事情以及我正在尝试做的事情。
typedef enum {
RED = 0,GREEN,BLUE,PURPLE,YELLOW
} colours_t;
typedef struct {
const char *name;
const size_t number_of_preferences;
const colours_t *ordered_preferences;
} colour_preferences_t;
// this way works,but is tedious
const colours_t bob_preferences[] = {RED,GREEN};
const colours_t alice_preferences[] = {BLUE,YELLOW};
const colours_t eve_preferences[] = {YELLOW,RED};
const colour_preferences_t array_of_preferences[3] = {
{"Bob",2,bob_preferences},{"Alice",3,alice_preferences},{"Eve",eve_preferences}
};
// this is how I'd like to do it (but it isn't valid)
const colour_preferences_t array_of_preferences_invalid[3] = {
{"Bob",{RED,GREEN}},{BLUE,YELLOW}},1,{YELLOW,RED}},};
更新:由于下面的回答,我已经找到了解决方案。并使用一个可变宏,甚至可以显式删除大小:
#define PREFERENCE_LIST(...) sizeof((colours_t[]) { __VA_ARGS__ })/sizeof(colours_t),(colours_t[]){ __VA_ARGS__ }
const colour_preferences_t array_of_preferences_short[3] = {
{"Bob",PREFERENCE_LIST(RED,GREEN)},PREFERENCE_LIST(BLUE,YELLOW)},PREFERENCE_LIST(YELLOW,RED)}
};