[英]Generate nested constant arrays in C at compile time
I'm trying to generate a large constant lookup table at compile time in C (C99), and each entry to the lookup table has a pointer to another const array.我试图在 C (C99) 编译时生成一个大的常量查找表,并且查找表的每个条目都有一个指向另一个常量数组的指针。 I'd like to be able to build all of these arrays all at once, but this isn't possible because a brace initialiser can't be used for a pointer.
我希望能够一次构建所有这些数组,但这是不可能的,因为大括号初始化器不能用于指针。 Is there some preprocessor macro or other trick I can use to define "anonymous" arrays or something similar so that I can include them in a nested data structure?
是否有一些预处理器宏或其他技巧可以用来定义“匿名”数组或类似的东西,以便我可以将它们包含在嵌套数据结构中?
I've created an example below, showing what I am currently doing, and also what I am trying to do.我在下面创建了一个示例,显示了我目前正在做的事情以及我正在尝试做的事情。
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, PURPLE, 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", 2, 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", 2, {RED, GREEN}},
{"Alice", 3, {BLUE, PURPLE, YELLOW}},
{"Eve", 1, {YELLOW, RED}},
};
Update: Thanks to the answers below, I have worked out a solution.更新:多亏了下面的答案,我已经找到了一个解决方案。 And using a varadic macro, I can even drop typing out the size explicitly:
使用 varadic 宏,我什至可以显式地输入大小:
#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)},
{"Alice", PREFERENCE_LIST(BLUE, PURPLE, YELLOW)},
{"Eve", PREFERENCE_LIST(YELLOW, RED)}
};
you need to create the object, and pointer to this object has to be the initializer of this field.您需要创建对象,并且指向该对象的指针必须是该字段的初始值设定项。 You can archive it by using the compound literals
您可以使用复合文字将其存档
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}},
};
It should work using a compound literal like this:它应该使用像这样的复合文字:
const colour_preferences_t array_of_preferences_invalid[3] = {
{"Bob", 2, (colours_t[]){RED, GREEN}},
{"Alice", 3, (colours_t[]){BLUE, PURPLE, YELLOW}},
{"Eve", 1, (colours_t[]){YELLOW, RED}},
};
You can read the details about compound literals here您可以在此处阅读有关复合文字的详细信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.