c中的查找表 [英] lookup table in c

查看:12
本文介绍了c中的查找表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 C 创建一个查找表当我定义这个时:

I'm creating a lookup table in C When 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"}}
};

我收到以下错误:

错误:灵活初始化嵌套上下文中的数组成员

error: initialization of flexible array member in a nested context

错误:(接近初始化为‘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:

结构或联合不应包含不完整或函数类型的成员(因此,结构不应包含自身的实例,但可以包含指向实例的指针本身),除了具有多个命名成员的结构的最后一个成员可能有不完整的数组类型;这样的结构(以及任何包含,可能递归地,作为这种结构的成员)不应是结构的成员或数组的元素.

A structure or union shall not contain a member with incomplete or function type (hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself), except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array.

因此,请改用 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中的查找表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆