在编译时在C中生成嵌套常量数组

我正在尝试在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)}
};
hyx_hyx_hyx 回答:在编译时在C中生成嵌套常量数组

您需要创建对象,并且指向该对象的指针必须是该字段的初始化程序。您可以使用复合文字

对其进行存档
const colour_preferences_t array_of_preferences_invalid[3] = {
        {"Bob",2,( const colours_t[]){RED,GREEN}},{"Alice",3,(const colours_t[]){BLUE,PURPLE,YELLOW}},{"Eve",1,(const colours_t[]){YELLOW,RED}},};
,

它应该使用这样的复合文字进行工作:

const colour_preferences_t array_of_preferences_invalid[3] = {
        {"Bob",(colours_t[]){RED,(colours_t[]){BLUE,(colours_t[]){YELLOW,};

您可以阅读有关复合文字here

的详细信息
本文链接:https://www.f2er.com/2825186.html

大家都在问