问题描述
我正在用 C 创建一个查找表当我定义这个时:
I'm creating a lookup table in CWhen I define this:
typedef struct {
char* action;
char* message;
} lookuptab;
lookuptab tab[] = {
{"aa","bb"},
{"cc","dd"}
};
它编译没有错误,但是当我做这样的事情时:
it compiles without errors but when I do something like this:
typedef struct {
char* action;
char* message[];
} lookuptab;
lookuptab tab[] = {
{"aaa", {"bbbb", "ccc"}},
{"cc", {"dd", "eeeee"}}
};
我收到以下错误:
错误:灵活初始化嵌套上下文中的数组成员
错误:(接近初始化为‘tab[0].message’)
error: (near initialization for ‘tab[0].message’)
如何初始化第二个示例中的选项卡数组?注意:我知道 tab 数组中的所有值.
How can I initialize the tab array in the second example?Note: I know all the values inside the tab array.
更新:消息的大小可能不同,例如
UPDATE: message could be of different size, e.g
typedef struct {
char* action;
char* message[];
} lookuptab;
lookuptab tab[] = {
{"aaa", {"bbbb", "ccc", "dd"}},
{"cc", {"dd", "eeeee"}}
};
非常感谢.
最好的问候,维克多
推荐答案
您不能使用在(结构的)数组中包含灵活数组成员的结构.参见 C99 标准 §6.7.2.1/2:
You can't use structures containing a flexible array member in an array (of the structure). See C99 standard §6.7.2.1/2:
结构或联合不应包含不完整或函数类型的成员(因此,结构不应包含自身的实例,但可以包含指向实例的指针本身),除了具有多个命名成员的结构的最后一个成员可能有不完整的数组类型;这样的结构(以及任何包含,可能递归地,作为这种结构的成员)不应是结构的成员或数组的元素.
因此,请改用 char **
(并担心您如何知道有多少条目):
So, use a char **
instead (and worry about how you know how many entries there are):
typedef struct
{
const char *action;
const char * const *message;
} lookuptab;
static const lookuptab tab[] =
{
{ "aaa", (const char * const []){ "bbbb", "ccc" } },
{ "cc", (const char * const []){ "dd", "eeeee" } }
};
这使用 C99 构造(第 6.5.2.5 节复合文字) - 如果您不使用 C99 编译器,请注意.
This uses a C99 construct (§6.5.2.5 Compound literals) - beware if you are not using a C99 compiler.
这篇关于c中的查找表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!